【发布时间】:2018-07-23 16:00:33
【问题描述】:
所有教程都告诉我数据库连接是一种宝贵的资源。我们必须在对其进行一些操作后关闭它。当我们想做另一件事时重新打开它。但我只找到一个指示连接状态的属性(打开) .
这意味着我需要为每个查询|更新|删除创建连接对象? 如果我不为每个操作创建连接(代码如下),如何安全地销毁连接?
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()
#do other things ..............................
#maby return here and do not execute below
#occur error below
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * from categories"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
【问题讨论】:
-
您可以将其保留用于多个查询,但如果您使用线程,则应检查其线程安全级别 (python.org/dev/peps/pep-0249/#threadsafety)。