python - SQLite3内存数据库到磁盘的纯Python备份

标签 python sqlite database-backups

如果不安装附加模块,如何使用 SQLite backup API将内存数据库备份到磁盘数据库?我已经成功地执行了磁盘到磁盘的备份,但是将已经存在的内存连接传递给 sqlite3_backup_init功能似乎是问题所在。

我的玩具示例,改编自 https://gist.github.com/achimnol/3021995并降到最低,如下:

import sqlite3
import ctypes

# Create a junk in-memory database
sourceconn = sqlite3.connect(':memory:')
cursor = sourceconn.cursor()
cursor.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
sourceconn.commit()

target = r'C:\data\sqlite\target.db'
dllpath = u'C:\\Python27\DLLs\\sqlite3.dll'

# Constants from the SQLite 3 API defining various return codes of state.
SQLITE_OK = 0
SQLITE_ERROR = 1
SQLITE_BUSY = 5
SQLITE_LOCKED = 6
SQLITE_OPEN_READONLY = 1
SQLITE_OPEN_READWRITE = 2
SQLITE_OPEN_CREATE = 4

# Tweakable variables
pagestocopy = 20
millisecondstosleep = 100

# dllpath = ctypes.util.find_library('sqlite3') # I had trouble with this on Windows
sqlitedll = ctypes.CDLL(dllpath)
sqlitedll.sqlite3_backup_init.restype = ctypes.c_void_p

# Setup some ctypes
p_src_db = ctypes.c_void_p(None)
p_dst_db = ctypes.c_void_p(None)
null_ptr = ctypes.c_void_p(None)

# Check to see if the first argument (source database) can be opened for reading.
# ret = sqlitedll.sqlite3_open_v2(sourceconn, ctypes.byref(p_src_db), SQLITE_OPEN_READONLY, null_ptr)
#assert ret == SQLITE_OK
#assert p_src_db.value is not None

# Check to see if the second argument (target database) can be opened for writing.
ret = sqlitedll.sqlite3_open_v2(target, ctypes.byref(p_dst_db), SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, null_ptr)
assert ret == SQLITE_OK
assert p_dst_db.value is not None

# Start a backup.
print 'Starting backup to SQLite database "%s" to SQLite database "%s" ...' % (sourceconn, target)
p_backup = sqlitedll.sqlite3_backup_init(p_dst_db, 'main', sourceconn, 'main')
print '    Backup handler: {0:#08x}'.format(p_backup)
assert p_backup is not None

# Step through a backup.
while True:
    ret = sqlitedll.sqlite3_backup_step(p_backup, pagestocopy)
    remaining = sqlitedll.sqlite3_backup_remaining(p_backup)
    pagecount = sqlitedll.sqlite3_backup_pagecount(p_backup)
    print '    Backup in progress: {0:.2f}%'.format((pagecount - remaining) / float(pagecount) * 100)
    if remaining == 0:
        break
    if ret in (SQLITE_OK, SQLITE_BUSY, SQLITE_LOCKED):
        sqlitedll.sqlite3_sleep(millisecondstosleep)

# Finish the bakcup
sqlitedll.sqlite3_backup_finish(p_backup)

# Close database connections
sqlitedll.sqlite3_close(p_dst_db)
sqlitedll.sqlite3_close(p_src_db)

我收到一个错误 ctypes.ArgumentError: argument 3: <type 'exceptions.TypeError'>: Don't know how to convert parameter 3在第 49 行 (p_backup = sqlitedll.sqlite3_backup_init(p_dst_db, 'main', sourceconn, 'main'))。不知何故,我需要将对内存数据库的引用传递给该 sqlite3_backup_init 函数。

我对C的了解不够多,无法掌握API的细节本身。

设置:Windows 7,ActiveState Python 2.7

最佳答案

从 Python 3.7 开始,此功能在 standard library 中可用。 .以下是直接从官方文档中复制的一些示例:

Example 1, copy an existing database into another:



import sqlite3

def progress(status, remaining, total):
    print(f'Copied {total-remaining} of {total} pages...')

con = sqlite3.connect('existing_db.db')
bck = sqlite3.connect('backup.db')
with bck:
    con.backup(bck, pages=1, progress=progress)
bck.close()
con.close()

Example 2, copy an existing database into a transient copy:



import sqlite3

source = sqlite3.connect('existing_db.db')
dest = sqlite3.connect(':memory:')
source.backup(dest)

为了回答您将内存数据库备份到磁盘的具体问题,它看起来很有效。这是使用标准库 backup 的快速脚本方法:

import sqlite3


source = sqlite3.connect(':memory:')
dest = sqlite3.connect('backup.db')

c = source.cursor()
c.execute("CREATE TABLE test(id INTEGER PRIMARY KEY, msg TEXT);")
c.execute("INSERT INTO test VALUES (?, ?);", (1, "Hello World!"))
source.commit()

source.backup(dest)

dest.close()
source.close()

backup.db数据库可以加载到sqlite3并检查:
$ sqlite3 backup.db
SQLite version 3.24.0 2018-06-04 14:10:15
Enter ".help" for usage hints.
sqlite> .schema
CREATE TABLE test(id INTEGER PRIMARY KEY, msg TEXT);
sqlite> SELECT * FROM test;
1|Hello World!

关于python - SQLite3内存数据库到磁盘的纯Python备份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23395888/

相关文章:

python - CuDNNLSTM(而不是 LSTM)层的意外结果

python - Pandas 分组并根据条件添加列数据

python - cPickle.UnpicklingError : pickle data was truncated

android - 我们可以将已准备好的SQLITE数据库用于手机应用程序吗?

cassandra - 在 Kubernetes 下管理 Cassandra 数据存储大小和备份

python - python manage.py createsuperuser 有什么用?

Android 设备上的 Javafxports 和 SQLite

ios - FMDB SQLite 没有出现在我的设备中

mysql - 如何根据主键仅在不存在的情况下插入记录? (与查询本身而不是表进行比较)

cassandra - Cassandra能否交替进行增量备份和全量备份?