JPC
JPC

Reputation: 8276

Python and sqlite3 - importing and exporting databases

I'm trying to write a script to import a database file. I wrote the script to export the file like so:

import sqlite3

con = sqlite3.connect('../sqlite.db')
with open('../dump.sql', 'w') as f:
    for line in con.iterdump():
        f.write('%s\n' % line)

Now I want to be able to import that database. I have tried :

import sqlite3

con = sqlite3.connect('../sqlite.db')
f = open('../dump.sql','r')
str = f.read()
con.execute(str)

but I'm not allowed to execute more than one statement. Is there a way to get it to run an SQL script directly?

Upvotes: 20

Views: 25617

Answers (2)

RichardTheKiwi
RichardTheKiwi

Reputation: 107686

Try using

con.executescript(str)

Documentation

Connection.executescript(sql_script)
    This is a nonstandard shortcut that creates an intermediate cursor object
    by calling the cursor method, then calls the cursor’s executescript
    method with the parameters given.

Or create the cursor first

import sqlite3

con = sqlite3.connect('../sqlite.db')
f = open('../dump.sql','r')
str = f.read()
cur = con.cursor()
cur.execute(str)

Upvotes: 5

mechanical_meat
mechanical_meat

Reputation: 169274

sql = f.read() # watch out for built-in `str`
cur.executescript(sql)

Documentation.

Upvotes: 25

Related Questions