从磁盘获取sqlite3数据库,将其加载到内存,然后将其保存到磁盘? [英] Get sqlite3 database from disk, load it to memory, and save it to disk?

查看:810
本文介绍了从磁盘获取sqlite3数据库,将其加载到内存,然后将其保存到磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做的是将一个sqlite3数据库从磁盘加载到内存中,使用它,并在脚本退出时将内存数据库保存到磁盘中.我将如何去做呢?谢谢!

What I need to do is load an sqlite3 database from the disk into memory, work with it, and when the script exits save the in-memory database to the disk. How would I go about doing this? Thanks!

推荐答案

所有您需要做的就是 connect 到数据库-然后您可以对它进行任何操作.

All you need to do is connect to the database - you can do anything you want to with it then.

from sqlite3 import connect

conn = connect("/path/to/your/sqlite.db")
# Do what you need to with the database here
# Changes (inserts, updates, etc) will be persisted
# to disk whenever you commit a transaction.

如果您需要能够运行一系列命令并在不成功的情况下将它们全部回滚,则应使用

If you need to be able to run a series of commands and roll them all back if one does not succeed you should use a transaction.

如果您需要复制现有数据库,请对其进行更改,然后将其保存在其他位置仅当更改成功时,您才能执行以下操作之一:

If you need to make a copy of the existing database, make alterations to it and then save it somewhere else only if the alterations succeed then you can do one of the following things:

  • 创建一个内存数据库,然后使用SQLite的 ATTATCH DATABASE 命令附加现有数据库到新的内存数据库.将所有数据从现有数据库复制到内存数据库中并进行转换后,您可以附加新数据库并再次复制所有内容.
  • 复制现有数据库文件,尝试对其进行更改,如果操作失败,则删除新文件.
  • 使用sqlite3 Connection.iterdump 以SQL脚本的形式获取表的内容,然后可以将其传递给 this答案建议(为新数据库使用内存中或磁盘上的连接字符串).
  • Create an in-memory database and then use SQLite's ATTATCH DATABASE command to attach the existing database to the new in-memory database. Once you have copied all of the data over from the existing database into the in-memory database and transformed it you can attach a new database and copy everything over again.
  • Copy the existing database file, attempt to make alterations to it, and delete the new file if the operations did not succeed.
  • Use sqlite3's Connection.iterdump to get the contents of the tables as a SQL script which you can then pass to sqlite3.Cursor.executescript as this answer suggests (using either an in-memory or an on-disk connection string for your new database).

这篇关于从磁盘获取sqlite3数据库,将其加载到内存,然后将其保存到磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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