如何将现有的 db 文件加载到 Python sqlite3 中的内存中? [英] How to load existing db file to memory in Python sqlite3?

查看:77
本文介绍了如何将现有的 db 文件加载到 Python sqlite3 中的内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的 sqlite3 db 文件,我需要对其进行一些广泛的计算.从文件中进行计算非常缓慢,而且由于文件不大(~10 MB),因此将其加载到内存中应该没有问题.

I have an existing sqlite3 db file, on which I need to make some extensive calculations. Doing the calculations from the file is painfully slow, and as the file is not large (~10 MB), so there should be no problem to load it into memory.

是否有一种 Pythonic 的方法可以将现有文件加载到内存中以加快计算速度?

Is there a Pythonic way to load the existing file into memory in order to speed up the calculations?

推荐答案

这是我为我的 Flask 应用程序编写的代码片段:

Here is the snippet that I wrote for my flask application:

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

这篇关于如何将现有的 db 文件加载到 Python sqlite3 中的内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆