我有一个现有的sqlite3 db文件,需要对其进行一些广泛的计算。从文件中进行计算非常缓慢,而且由于文件不太大(~10 MB),因此将其加载到内存中应该没有问题。
是否有一种Pythonic方式将现有文件加载到内存中以加快计算速度?
发布于 2012-06-01 19:46:07
下面是我为我的烧瓶应用程序编写的片段:
import sqlite3
from io 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\n' % 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发布于 2018-11-11 20:50:58
那sqlite3.Connection.backup(...)呢?“这种方法即使在被其他客户端访问时,或者通过相同的连接同时进行SQLite数据库的备份。”可用性: SQLite 3.6.11或更高版本。新版本3.7。
import sqlite3
source = sqlite3.connect('existing_db.db')
dest = sqlite3.connect(':memory:')
source.backup(dest)发布于 2010-10-03 15:02:19
sqlite3.Connection.iterdump“返回一个迭代器以SQL文本格式转储数据库。在保存内存中的数据库以便以后恢复时非常有用。此函数提供与sqlite3 shell中的.dump命令相同的功能。
获取这样一个迭代器,并将基于磁盘的数据库转储到基于内存的数据库中,您就可以进行计算了。当计算完成后,只需将相反的方式转储回磁盘。
https://stackoverflow.com/questions/3850022
复制相似问题