Python和sqlite3 - 导入和导出数据库

时间:2011-01-17 23:45:44

标签: python sql django sqlite

我正在尝试编写一个脚本来导入数据库文件。我编写了脚本来导出文件,如下所示:

import sqlite3

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

现在我希望能够导入该数据库。我试过了:

import sqlite3

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

但我不允许执行多个语句。有没有办法让它直接运行SQL脚本?

2 个答案:

答案 0 :(得分:17)

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

Documentation

答案 1 :(得分:4)

尝试使用

con.executescript(str)

文档

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.

或先创建光标

import sqlite3

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