Use python and psycopg2 to execute a sql file that contains a DROP DATABASE statement

女生的网名这么多〃 提交于 2019-12-11 02:27:26

问题


I am trying to use a python function to execute a .sql file.

The sql file begins with a DROP DATABASE statement.
The first lines of the .sql file look like this:

DROP DATABASE IF EXISTS myDB; 
CREATE DATABASE myDB;

The rest of the .sql file defines all the tables and views for 'myDB'

Python Code:

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

When I run the connect() function, I get an error on the DROP DATABASE statement.

ERROR:

psycopg2.InternalError: DROP DATABASE cannot be executed from a function or multi-command string

I spent a lot of time googling this error, and I can't find a solution.

I also tried adding an AUTOCOMMIT statement to the top of the .sql file, but it didn't change anything.

SET AUTOCOMMIT TO ON;

I am aware that postgreSQL doesn't allow you to drop a database that you are currently connected to, but I didn't think that was the problem here because I begin the connect() function by connecting to the template1 database, and from that connection create the cursor object which opens the .sql file.

Has anyone else run into this error, is there any way to to execute the .sql file using a python function?


回答1:


This worked for me for a file consisting of SQL Queries in each line:

sql_file = open('file.sql','r')
cursor.execute(sql_file.read())



回答2:


You are reading in the entire file and passing the whole thing to PostgreSQL as one string (as the error message says, "multi-command string". Is that what you are intending to do? If so, it isn't going to work.

Try this:

cursor.execute(sqlfile.readline())

Or, shell out to psql and let it do the work.



来源:https://stackoverflow.com/questions/36416405/use-python-and-psycopg2-to-execute-a-sql-file-that-contains-a-drop-database-stat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!