我想创建Postgres数据库使用Python。
con = psql.connect(dbname='postgres',
user=self.user_name, host='',
password=self.password)
cur = con.cursor()
cur.execute("CREATE DATABASE %s ;" % self.db_name)我收到以下错误:
InternalError: CREATE DATABASE cannot run inside a transaction block我正在使用psycopg2连接。我不明白有什么问题。我要做的是连接到数据库(Postgres):
psql -postgres -U UserName然后创建另一个数据库:
create database test;这是我通常做的事情,我想通过创建Python脚本来实现自动化。
发布于 2015-12-28 03:47:38
使用psycopg2扩展ISOLATION_LEVEL_AUTOCOMMIT:
发出命令时不会启动任何事务,并且不需要commit()或rollback()。
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT # <-- ADD THIS LINE
con = psycopg2.connect(dbname='postgres',
user=self.user_name, host='',
password=self.password)
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) # <-- ADD THIS LINE
cur = con.cursor()
# Use the psycopg2.sql module instead of string concatenation
# in order to avoid sql injection attacs.
cur.execute(sql.SQL("CREATE DATABASE {}").format(
sql.Identifier(self.db_name))
)发布于 2017-04-26 20:58:39
如另一个答案所示,连接必须处于自动提交模式。另一种使用psycopg2设置它的方法是通过autocommit属性:
import psycopg2
from psycopg2 import sql
con = psycopg2.connect(...)
con.autocommit = True
cur = con.cursor()
# sql.SQL and sql.Identifier are needed to avoid SQL injection attacks.
cur.execute(sql.SQL('CREATE DATABASE {};').format(
sql.Identifier(self.db_name)))https://stackoverflow.com/questions/34484066
复制相似问题