如何使程序等待sqlite数据库的锁定

时间:2015-11-11 23:45:36

标签: python sqlite python-2.x

我有一个程序作为更大进程的一部分运行,其唯一目的是将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)

1 个答案:

答案 0 :(得分:1)

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可以在幕后为您实现此类事情(也许我错了)

相关问题