上下文管理器连接数据库示例

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>
关闭数据库了
原文地址:https://www.cnblogs.com/qxh-beijing2016/p/15623672.html