使用python和psycopg2执行包含DROP DATABASE语句的sql文件

ste*_*vec 7 python sql postgresql psycopg2 python-2.7

我正在尝试使用 python 函数来执行 .sql 文件。

sql 文件以DROP DATABASE语句开头。
.sql 文件的第一行如下所示:

DROP DATABASE IF EXISTS myDB; 
CREATE DATABASE myDB;
Run Code Online (Sandbox Code Playgroud)

.sql 文件的其余部分定义了“myDB”的所有表和视图

蟒蛇代码:

def connect():
    conn = psycopg2.connect(dbname='template1', user='user01')
    conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
    cursor = conn.cursor()

    sqlfile = open('/path/to/myDB-schema.sql', 'r')
    cursor.execute(sqlfile.read())

    db = psycopg2.connect(dbname='myDB', user='user01')
    cursor = db.cursor()
    return db,cursor
Run Code Online (Sandbox Code Playgroud)

当我运行该connect()函数时,我在DROP DATABASE语句中收到错误消息。

错误:

psycopg2.InternalError: DROP DATABASE cannot be executed from a function or multi-command string
Run Code Online (Sandbox Code Playgroud)

我花了很多时间在谷歌上搜索这个错误,但找不到解决方案。

我还尝试在 .sql 文件的顶部添加一个 AUTOCOMMIT 语句,但它没有改变任何东西。

SET AUTOCOMMIT TO ON;
Run Code Online (Sandbox Code Playgroud)

我知道 postgreSQL 不允许您删除当前连接到的数据库,但我不认为这是这里的问题,因为我通过连接到 template1 数据库开始了 connect() 函数,然后从那里开始连接创建打开 .sql 文件的游标对象。

有没有其他人遇到过这个错误,有没有办法使用 python 函数执行 .sql 文件?

Yan*_*kee 5

这对我来说适用于每行包含 SQL 查询的文件:

sql_file = open('file.sql','r')
cursor.execute(sql_file.read())
Run Code Online (Sandbox Code Playgroud)


jja*_*nes 0

您正在读取整个文件并将整个文件作为一个字符串传递给 PostgreSQL(如错误消息所示,“多命令字符串”)。这是您打算做的吗?如果是这样,它将无法工作。

尝试这个:

cursor.execute(sqlfile.readline())
Run Code Online (Sandbox Code Playgroud)

或者,花钱psql让它完成工作。

  • 谢谢,@jjane 我开始认为使用: `subprocess.call('psql -f mydb.sql', shell=True)` 会更容易 (2认同)