PostgreSQL CREATE DATABASE 无法在事务块内运行

问题描述 投票:0回答:2

我正在尝试在 Postgre SQL Python 中创建数据库,但出现错误:CREATE DATABASE 无法在事务块内运行。我读过你需要自动提交,但我已经有了。有什么问题

try:
    with psycopg2.connect(
        host=host,
        user=rootUser,
        password=rootPassword,
    ) as connection:
        connection.autocommit = True
        with connection.cursor() as cursor:
            cursor.execute(
                ("CREATE DATABASE " + db_name + """ WITH
                OWNER = """ + user + """ ENCODING = 'UTF8'
                CONNECTION LIMIT = -1
                IS_TEMPLATE = False;""")
            )
python database postgresql psycopg2
2个回答
0
投票

自 v2.9 起,

with conn
启动交易,因此它不能用于执行
CREATE DATABASE
等必须在交易外发出的操作。

您可以在不使用上下文管理器的情况下完成此操作:

try:
    conn = psycopg2.connect(dbname='postgres')
    conn.autocommit = True
    with conn.cursor() as cur:
        cur.execute('CREATE DATABASE foo')
finally:
    conn.close()

或者像这样

import contextlib

with contextlib.closing(psycopg2.connect(dbname='postgres')) as conn:
    conn.autocommit = True
    with conn.cursor() as cur:
        cur.execute('CREATE DATABASE foo')

-1
投票

首先你必须确保你使用的 psycopg 版本支持自动提交,即 2.73 或更高版本。另外,在通过修改代码创建光标之前,您必须将

autocommit
设置为
True

try:
    with psycopg2.connect(
        host=host,
        user=rootUser,
        password=rootPassword,
        autocommit=True,
    ) as connection:
        with connection.cursor() as cursor:
            cursor.execute(
                ("CREATE DATABASE " + db_name + """ WITH
                OWNER = """ + user + """ ENCODING = 'UTF8'
                CONNECTION LIMIT = -1
                IS_TEMPLATE = False;""")
            )
except psycopg2.Error as e:
    print("Error:", e)
© www.soinside.com 2019 - 2024. All rights reserved.