Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
JPC Avatar asked Jan 17 '11 23:01

JPC


People also ask

How do I populate a SQLite database in Python?

First, connect to the SQLite database by creating a Connection object. Second, create a Cursor object by calling the cursor method of the Connection object. Third, execute an INSERT statement. If you want to pass arguments to the INSERT statement, you use the question mark (?) as the placeholder for each argument.


1 Answers

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

Documentation.

like image 61
mechanical_meat Avatar answered Oct 10 '22 06:10

mechanical_meat