使用 python 创建 Postgres 数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34484066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a Postgres database using python
提问by kiran6
I want to create Postgres database using Python.
我想使用 Python 创建 Postgres 数据库。
con = psql.connect(dbname='postgres',
user=self.user_name, host='',
password=self.password)
cur = con.cursor()
cur.execute("CREATE DATABASE %s ;" % self.db_name)
I am getting the following error:
我收到以下错误:
InternalError: CREATE DATABASE cannot run inside a transaction block
I am using psycopg2 to connect. I don't understand what's the problem. What am I trying to do is to connect to database (Postgres):
我正在使用 psycopg2 进行连接。我不明白有什么问题。我想要做的是连接到数据库(Postgres):
psql -postgres -U UserName
And then create another database:
然后创建另一个数据库:
create database test;
This is what I usually do and I want to automate this by creating Python script.
这就是我通常所做的,我想通过创建 Python 脚本来自动执行此操作。
采纳答案by Tommaso Di Bucchianico
Use ISOLATION_LEVEL_AUTOCOMMIT, a psycopg2 extensions:
使用ISOLATION_LEVEL_AUTOCOMMIT,一个 psycopg2 扩展:
No transaction is started when command are issued and no commit() or rollback() is required.
发出命令时不会启动任何事务,并且不需要 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))
)
回答by álvaro Marco
As shown in the other answer the connection must be in autocommit mode. Another way of setting it using psycopg2
is through the autocommit
attribute:
如另一个答案所示,连接必须处于自动提交模式。另一种设置它的方法psycopg2
是通过autocommit
属性:
import psycopg2
con = psycopg2.connect(...)
con.autocommit = True
cur = con.cursor()
cur.execute('CREATE DATABASE {};'.format(self.db_name))