要使用 Python 在 PostgreSQL 中更好地初始化、执行和提交?

To init, execute and commit better in PostgreSQL with Python?

我在 PostgeSQL 9.4 和 Python 2.7.9

中使用的代码
import psycopg2
import psycopg2.extras

def init_pg94_from_sql_file(filename, connection):
    ...
    cursor = connection.cursor()
    cursor.execute(...)    
    connection.commit()     
    cursor.close()

def store_values_to_pg94(fileHeader, file_size, eventStarts, eventEnds, connection): 
    cursor = connection.cursor()
    cursor.execute(...);
    connection.commit()     
    cursor.close()

def(main):
...
    conn_string = "dbname=detector_development user=postgres"
    conn = psycopg2.connect(conn_string)
    init_pg94_from_sql_file("12.7.2015.sql", conn)
    store_values_to_pg94(fileHeader, file_size, eventStarts, eventEnds, conn)

    conn.commit()
    conn.close()

你在哪里看到

我认为这里可能有很多重复,因为在每个函数中通过提交写入磁盘听起来效率很低。 还关闭了三次听起来效率太低了。

如何更好地处理游标初始化和提交?

游标是轻量级的。关闭游标就是释放未使用的内存。在数据库连接中,每个事务都应该被提交。承担每一项任务。效率是数据库工作的一部分。如果未提交的数据写入磁盘或何时写入提交的数据,则不是您关心的问题。