如何将现有的数据库文件加载到Python sqlite3中的内存中?

发布于 2021-01-29 19:35:28

我有一个现有的sqlite3db文件,需要在其上进行一些广泛的计算。从文件进行计算非常缓慢,并且文件不大(〜10 MB),因此将其加载到内存应该没有问题。

是否有Python方式将现有文件加载到内存中以加快计算速度?

关注者
0
被浏览
98
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看