Python与sqlite3 - 导入和导出数据库
我正在尝试写一个脚本来导入一个数据库文件。我写了一个脚本来导出这个文件,代码如下:
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 个回答
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)
24
sql = f.read() # watch out for built-in `str`
cur.executescript(sql)
文档链接。