Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 565
stevec Avatar asked Apr 05 '16 03:04

stevec


Video Answer


1 Answers

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())
like image 167
Yankee Avatar answered Sep 23 '22 02:09

Yankee