【问题标题】:In pymysql of python can I keep a connection object for next use?在 python 的 pymysql 中,我可以保留一个连接对象以供下次使用吗?
【发布时间】: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 pymysql


【解决方案1】:

通常,您的程序会打开一个数据库连接并保持打开状态,直到程序完成。创建/打开连接是一项昂贵的操作,因此通常您只想在程序运行期间保持打开状态。在创建连接期间,数据库必须为该连接分配资源。如果您要为每个操作打开和关闭一个连接,这将对整个数据库性能产生负面影响,因为数据库需要独占访问这些内存结构并导致等待。

【讨论】:

    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多