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

复制代码
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>
关闭数据库了

 

posted @   乔小生1221  阅读(76)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示