我有一个现有的sqlite3 db文件,需要在其上进行一些广泛的计算。 从文件进行计算非常缓慢,并且文件不大(?10 MB),因此将其加载到内存应该没有问题。
是否有Python方式将现有文件加载到内存中以加快计算速度?
这是我为flask应用程序编写的代码段:
import sqlite3
from StringIO import StringIO
def init_sqlite_db(app):
# Read database to tempfile
con = sqlite3.connect(app.config['SQLITE_DATABASE'])
tempfile = StringIO()
for line in con.iterdump():
tempfile.write('%s
' % line)
con.close()
tempfile.seek(0)
# Create a database in memory and import from tempfile
app.sqlite = sqlite3.connect(":memory:")
app.sqlite.cursor().executescript(tempfile.read())
app.sqlite.commit()
app.sqlite.row_factory = sqlite3.Row
sqlite3.Connection.iterdump" [r返回迭代器以SQL文本格式转储数据库。在保存内存数据库以供以后还原时很有用。此功能提供的功能与sqlite3 Shell中的.dump命令相同。
获取这样的迭代