使用python创建Postgres数据库 [英] Create a Postgres database using python

查看:200
本文介绍了使用python创建Postgres数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python创建Postgres数据库。

I want to create Postgres database using 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):

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):

psql -postgres -U UserName

然后创建另一个数据库:

And then create another database:

create database test;

这是我通常要做的,我想通过创建Python脚本来实现此自动化。

This is what I usually do and I want to automate this by creating Python script.

推荐答案

使用 ISOLATION_LEVEL_AUTOCOMMIT ,psycopg2扩展:

Use ISOLATION_LEVEL_AUTOCOMMIT, a psycopg2 extensions:


在发出命令时没有事务开始,也没有commit()或
rollback()是必需的。

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



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))
    )

这篇关于使用python创建Postgres数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆