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

[英]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?

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

2 个解决方案

#1


15  

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

Documentation.

文档。

#2


3  

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)
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2011/01/17/14bb6efef4fc3c681dcf4339c23764a4.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告