nag*_*lzs 3 python psycopg2 python-3.x psycopg3
这不起作用:
conn = psycopg.connect(dsn)
conn.execute("CREATE DATABASE test")
Run Code Online (Sandbox Code Playgroud)
以下是有关 psycopg3 中交易的文档:https://www.psycopg.org/psycopg3/docs/basic/transactions.html
对于这个问题最重要的说法是:
与 psql 相比,Psycopg 的行为可能看起来令人惊讶:默认情况下,任何数据库操作都会启动一个新事务。
这是一个相当长的页面,但它没有告诉任何地方如何在不启动新事务的情况下执行语句。有一个autocommit=True论据connect(),但它也不起作用。
无论我做什么,我总是会收到此错误:
psycopg.errors.ActiveSqlTransaction: CREATE DATABASE cannot run inside a transaction block
Run Code Online (Sandbox Code Playgroud)
如何使用 psycopg3 创建数据库?
使用自动提交连接对我有用:
\n>>> conn = psycopg.connect(dbname=\'postgres\', autocommit=True)\n>>> cur = conn.cursor()\n>>> cur.execute(\'drop database if exists test3\')\n<psycopg.Cursor [COMMAND_OK] [IDLE] (user=xxx database=postgres) at 0x7f438ef92f00>\n>>> cur.execute(\'create database test3\')\n<psycopg.Cursor [COMMAND_OK] [IDLE] (user=xxx database=postgres) at 0x7f438ef92f00>\n>>> \nRun Code Online (Sandbox Code Playgroud)\n>>> conn = psycopg.connect(dbname=\'postgres\', autocommit=True)\n>>> cur = conn.cursor()\n>>> cur.execute(\'drop database if exists test3\')\n<psycopg.Cursor [COMMAND_OK] [IDLE] (user=xxx database=postgres) at 0x7f438ef92f00>\n>>> cur.execute(\'create database test3\')\n<psycopg.Cursor [COMMAND_OK] [IDLE] (user=xxx database=postgres) at 0x7f438ef92f00>\n>>> \nRun Code Online (Sandbox Code Playgroud)\n