Python中如何安全地关闭pymysql数据库连接?
我测试过。如果每次使用就创建 connection 对象并关闭要比一次创建用完再关闭慢 3 倍,但我的代码可能会像下面这样。如何安全关闭呢?目前想到的是把它封装到一个类并实现这个类的__del__。在 del 里关闭。但我想直接用函数,并且我觉得我没必要封装进去。如果是这样该如何弄?
connection = pymysql.connect(host=‘localhost’,
user=‘root’,
password=‘password’,
db=‘blog’,
charset=‘utf8’,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
# Read a single record
sql = “SELECT * from categories”
cursor.execute(sql)
result = cursor.fetchall()
print(result)
connection.close()
#做其它事 …
#这里可能直接返回
#执行下边出错
with connection.cursor() as cursor:
# Read a single record
sql = “SELECT * from categories”
cursor.execute(sql)
result = cursor.fetchall()
print(result)
Python中如何安全地关闭pymysql数据库连接?
在Python里用pymysql,安全关连接的关键就两点:用try...except...finally块,并且在finally里关。这样就算代码中间出异常,连接也保证能关掉,不会泄露。
直接看代码吧,这是最清楚的:
import pymysql
def query_database():
connection = None
cursor = None
try:
# 1. 建立连接
connection = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database',
charset='utf8mb4'
)
# 2. 执行操作
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table LIMIT 5")
results = cursor.fetchall()
for row in results:
print(row)
except pymysql.Error as e:
print(f"数据库操作出错: {e}")
finally:
# 3. 关键:在finally块里按顺序关闭
if cursor:
cursor.close()
if connection:
connection.close()
print("连接已安全关闭")
# 运行示例
if __name__ == "__main__":
query_database()
核心就这三点:
- 把连接和游标都放
try外面初始化成None,这样finally里才能判断。 - 所有数据库操作放
try里。 finally块必须关连接,而且要先关游标再关连接。
更Pythonic的写法是用with语句(pymysql支持),它能自动关:
import pymysql
def query_with_context_manager():
try:
with pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
) as connection:
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
result = cursor.fetchone()
print(result)
# 退出with块后连接自动关闭
except pymysql.Error as e:
print(f"出错: {e}")
query_with_context_manager()
总结:用finally块或者with语句来关连接。
都是池化管理 使用链接池是基础也是常规做法

