zoukankan      html  css  js  c++  java
  • 上下文管理器连接数据库示例

    import pymysql
    class DB_LINK():
        def __init__(self):
            self.pool_db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='test',
                                           charset='utf8', cursorclass=pymysql.cursors.DictCursor)
    
        def __enter__(self):
            self.coon = self.pool_db.cursor()
            return self.coon
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            print(exc_type)#异常类型
            print(exc_val)#异常实例
            print(exc_tb)#回溯选择
            if exc_val:
                self.coon.close()
                print('关闭数据库了')
            return False
    
    
    with DB_LINK() as db:
        db.execute('select * from user where age<2 and username="qxh" and id<500')
        print(db.fetchall())
    [{'id': 52, 'username': 'qxh', 'age': 1}, {'id': 128, 'username': 'qxh', 'age': 1}, {'id': 134, 'username': 'qxh', 'age': 1}, {'id': 229, 'username': 'qxh', 'age': 1}, {'id': 250, 'username': 'qxh', 'age': 1}, {'id': 426, 'username': 'qxh', 'age': 1}]
    None
    None
    None

    故意修改sql语句使其报错

    with DB_LINK() as db:
        db.execute('selecct * from user where age<2 and username="qxh" and id<500')
        print(db.fetchall())

    报错内容:

    Traceback (most recent call last):
      File "C:/Users/Administrator/Desktop/test/mysql_pool_test.py", line 113, in <module>
        db.execute('selecct * from user where age<2 and username="qxh" and id<500')
      File "D:\virtualenv\py3\lib\site-packages\pymysql\cursors.py", line 148, in execute
        result = self._query(query)
      File "D:\virtualenv\py3\lib\site-packages\pymysql\cursors.py", line 310, in _query
        conn.query(q)
      File "D:\virtualenv\py3\lib\site-packages\pymysql\connections.py", line 548, in query
        self._affected_rows = self._read_query_result(unbuffered=unbuffered)
      File "D:\virtualenv\py3\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
        result.read()
      File "D:\virtualenv\py3\lib\site-packages\pymysql\connections.py", line 1156, in read
        first_packet = self.connection._read_packet()
      File "D:\virtualenv\py3\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
        packet.raise_for_error()
      File "D:\virtualenv\py3\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
        err.raise_mysql_exception(self._data)
      File "D:\virtualenv\py3\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
        raise errorclass(errno, errval)
    pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'selecct * from user where age<2 and username="qxh" and id<500\' at line 1')
    <class 'pymysql.err.ProgrammingError'>
    (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'selecct * from user where age<2 and username="qxh" and id<500\' at line 1')
    <traceback object at 0x00000240B011A580>
    关闭数据库了

    终止异常:__exit__:return True

    <class 'pymysql.err.ProgrammingError'>
    (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'selecct * from user where age<2 and username="qxh" and id<500\' at line 1')
    <traceback object at 0x00000296676E9380>
    关闭数据库了
  • 相关阅读:
    eCharts_数据过多底部滚动条实现数据展示
    canvas_简单练习
    canvas_基于canvan绘制的双半圆环进度条
    js_读【javascript面向对象编程指南】笔记
    csc_滤镜filter和实现透明的两种方式
    jq_从右向右的滑入滑出效果
    textarea输入框实时统计输入字符数
    windows7_常用操作终端操作
    1080. Graduate Admission (30)
    1079. Total Sales of Supply Chain (25)
  • 原文地址:https://www.cnblogs.com/qxh-beijing2016/p/15623672.html
Copyright © 2011-2022 走看看