2015-12-27 9 views
14

Pythonを使用してPostgresデータベースを作成したいと思います。私は接続するためにpsycopg2を使用していますPythonを使用してPostgresデータベースを作成する

InternalError: CREATE DATABASE cannot run inside a transaction block 

con = psql.connect(dbname='postgres', 
     user=self.user_name, host='', 
     password=self.password) 

cur = con.cursor() 
cur.execute("CREATE DATABASE %s ;" % self.db_name) 

私は、次のエラーを取得しています。私は何が問題なのか分かりません。

psql -postgres -U UserName 

そして、別のデータベースを作成します: 私は何をしようとしていること(Postgresの)データベースに接続することです

create database test; 

これは私が通常何をすべきかと私は作成することによって、これを自動化したいですPythonスクリプト。

答えて

27

使用ISOLATION_LEVEL_AUTOCOMMIT、psycopg2拡張子:

No transaction is started when command are issued and no commit() or rollback() is required.

import psycopg2 
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() 
cur.execute("CREATE DATABASE %s ;" % self.db_name) 
+0

このコードは、エラー 'psqlの – Tommy

+0

をdefined'ないを生成ありがとう、私はエラーを取り除きます。 –

7

接続が自動コミットモードである必要があり、他の答えに示すように。 psycopg2を使用して、それを設定するもう一つの方法は、autocommit属性である:

import psycopg2 

con = psycopg2.connect(...) 
con.autocommit = True 

cur = con.cursor() 
cur.execute('CREATE DATABASE {};'.format(self.db_name)) 
関連する問題