如何在 Python sqlite3 中将现有的 db 文件加载到内存中?

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

问题描述

我有一个现有的 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
' % 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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)
Inserting NaN value into MySQL Database(将NaN值插入MySQL数据库)
Window functions not working in pd.read_sql; Its shows error(窗口函数在pd.read_sql中不起作用;它显示错误)
(Closed) Leaflet.js: How I can Do Editing Geometry On Specific Object I Select Only?((已关闭)Leaflet.js:如何仅在我选择的特定对象上编辑几何图形?)
Materialized view in oracle with Fast Refresh instead of complete dosnamp;#39;t work(Oracle中具有快速刷新功能的实例化视图,而不是完成大量工作(A))