如何在Python中关闭数据库连接
发布时间:2023-12-24 16:35:41
在Python中关闭数据库连接可以通过调用数据库连接对象的close()方法完成。下面是一个使用例子:
import mysql.connector
# 创建数据库连接
cnx = mysql.connector.connect(user='root', password='password', host='localhost', database='mydb')
# 创建游标对象
cursor = cnx.cursor()
# 执行查询语句
query = ("SELECT * FROM mytable")
cursor.execute(query)
# 获取查询结果
result = cursor.fetchall()
for row in result:
print(row)
# 关闭游标对象
cursor.close()
# 关闭数据库连接
cnx.close()
上述代码中,首先创建了一个MySQL数据库连接,并使用cursor()方法创建了一个游标对象。然后执行了一条查询语句,并使用fetchall()方法获取查询结果。接下来通过调用游标对象的close()方法关闭了游标对象,最后调用数据库连接对象的close()方法关闭数据库连接。
在实际开发中,为了避免忘记关闭数据库连接导致资源泄露,可以使用with语句来自动关闭数据库连接,如下所示:
import mysql.connector
# 创建数据库连接
with mysql.connector.connect(user='root', password='password', host='localhost', database='mydb') as cnx:
# 创建游标对象
with cnx.cursor() as cursor:
# 执行查询语句
query = ("SELECT * FROM mytable")
cursor.execute(query)
# 获取查询结果
result = cursor.fetchall()
for row in result:
print(row)
使用with语句后,会在执行完with代码块后自动调用close()方法关闭数据库连接,无需手动关闭。这样可以保证在任何情况下都能正确关闭数据库连接,确保资源的释放。
总结:
关闭数据库连接是保证程序安全性和资源释放的重要步骤。在Python中,可以通过调用数据库连接对象的close()方法来关闭数据库连接,也可以使用with语句来自动关闭数据库连接。
