如何让程序等待 sqlite 数据库上的锁

How to make a program wait for a lock on a sqlite database

我有一个程序 运行 作为更大进程的一部分,其唯一目的是将 sqlite 数据库安全地复制到另一个文件夹以进行备份。唯一的问题是我的产品 运行 刚刚关闭,因为数据库被其他进程锁定了。有没有一种方法可以让这个程序等待获得锁?如果它延迟程序的其余部分几秒钟就可以了。

这是我的代码:

import sqlite3
import shutil
import optparse
import os
import time
import logging

logging.basicConfig(level=logging.INFO, format="[%(levelname)s] - %(message)s")
logging.disable(logging.CRITICAL)

def sqlite3_backup(db_file, backup_dir):
    print 'DB is: ', db_file + '\n', 'Backup Dir is: ', backup_dir
    if not os.path.isdir(backup_dir):
        raise Exception("Backup directory does not exist: {0}".format(backup_dir))

    with sqlite3.connect(db_file) as conn:
        logging.info('Connected to the database.')
        cursor = conn.cursor()
        cursor.execute('begin immediate')
        shutil.copy(db_file, backup_dir)
        logging.info('Closing the database.')

usage = "%prog [options] db-file backup-dir"
description = """\
Backup sqlite3 database to a directory, appending a datestamp on the backup."""

def get_options():
    parser = optparse.OptionParser(usage=usage, description=description)
    opts, args = parser.parse_args()
    if len(args) != 2:
        raise parser.error("Incorrect number of parameters")

    opts.databasefile, opts.backupdir = args
    return opts

if __name__ == '__main__':
    opts = get_options()
    sqlite3_backup(opts.databasefile, opts.backupdir)
if __name__ == '__main__':
    opts = get_options()
    for i in range(90): #give up after 90 seconds
        try:
            sqlite3_backup(opts.databasefile, opts.backupdir)
        except sqlite3.OperationalError as e:
            if "locked" in str(e):
                 time.sleep(1)
            else:
                 raise
        else:
            sys.stdout.write("OK Backup sucess!")
            sys.exit(0)
   sys.stderr.write("Unable to aquire database lock...")
   sys.exit(1)

这是您可以执行此操作的一种方式...

我还建议使用 ORM,因为我认为大多数 ORM 可能会在幕后为您实现这类事情(也许我错了)