如何运行psycopg2。附加值()未提交?

2024-04-23 07:53:12 发布

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

我在跑步:

def db_connect():
    conn = psycopg2.connect(
        host=host,
        database=database, 
        user=user,
        password=password
    )
    return conn


data_to_insert = []
for a, b, c in data_source:  # len(data_source) > 100000
   data_to_insert.append(a, b, c) 


def insert_to_table():

    request = "INSERT INTO tablename " \ 
              "(a, b, c) " \
              "VALUES " \
              "%s "

    do_commit = False

    with db_connect() as conn:
        with conn.cursor() as cur:
                psycopg2.extras.execute_values(cur, request, data_to_insert, template=None)

        if do_commit:
            conn.commit() # this line could be completely omitted 

但它仍然承诺。有可能避免吗?如果我没记错的话,其他比较慢的方法,比如cur.execute(),都没有这个问题。你知道吗

psycopg2.__version__2.8.2 (dt dec pq3 ext lo64)

PostgreSQL 10.10(Ubuntu10.10-0ubuntu0.18.04.1)在x86泷u 64-pc-linux-gnu上,由gcc(Ubuntu7.4.0-1ubuntu1~18.04.1)7.4.0编译,64位


Tags: tohostsourcedbdatadefconnectpassword
1条回答
网友
1楼 · 发布于 2024-04-23 07:53:12

默认情况下,conn将在脱离with语句后提交。你知道吗

Starting from version 2.5, psycopg2’s connections and cursors are context managers and can be used with the with statement:

with psycopg2.connect(DSN) as conn:
    with conn.cursor() as curs:
        curs.execute(SQL) 

When a connection exits the with block, if no exception has been raised by the block, the transaction is committed. In case of exception the transaction is rolled back.

因此,与其这样做:

if do_commit:
    conn.commit()

if not do_commit:
    conn.rollback()

相关问题 更多 >