我需要在一个循环中创建多个数据库连接吗?

2024-04-19 15:22:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用sqllite3,并希望将数据插入表中。我的代码大致如下:

def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = sqlite3.connect(db)
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()

可以看到,每次插入数据记录时,数据库都是连接和关闭的。有没有办法只连接和关闭数据库一次,以便处理所有数据?你知道吗


Tags: to数据代码inadd数据库fordb
3条回答

最好在开始时打开数据库一次,然后通过创建一个全局变量在结束时关闭它。你知道吗

connection = sqlite3.connect(db)
cursor = connection.cursor()
def fill_database():
     ...
    for record in records:
       add_to_db(record)
 ...

def add_to_dbrecord):
   ..
   cursor.execute("...")
   connection.commit()

#end of script
connection.close()

如果您使用的是类,则可以使用单例设计模式
希望有帮助

如果您的代码在多线程或多处理上工作。所涉及的连接池将更高效。来自wiki的定义

In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database.

下面是来自sqlalchemy的exmaple。该池自动管理所有连接,并且在需要执行SQL时不需要创建新连接。你知道吗

import sqlalchemy.pool as pool

import psycopg2

def getconn():
    c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
    return c

mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)


def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = mypool.connect()
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()

这样效率更高。在每条记录之后提交数据会严重影响性能。你知道吗

def fill_database(db):
    ...
    connection = sqlite3.connect(db)
    cursor = connection.cursor()

    for record in records:
        cursor.execute("...")

    connection.commit()
    connection.close()

如果必须有单独的函数,则将游标作为参数而不是db传递。你知道吗

相关问题 更多 >