Python SQLite3备份参数

时间:2018-03-29 14:43:18

标签: python sqlite backup

我是SQLite的新手并且想知道如何为数据库创建备份,在类似的网站上我发现了一个关于如何为数据库创建备份的问题,但是我遇到了让它工作的问题。

这是一个问题:https://codereview.stackexchange.com/questions/78643/create-sqlite-backups

这是代码:

from __future__ import print_function
from __future__ import unicode_literals

import argparse
import sqlite3
import shutil
import time
import os

NO_OF_DAYS = 7

def sqlite3_backup(dbfile, backupdir):

dbfile = Accounts.db
backupdir = r"E:\TESTING\BackUp.db"
"""Create timestamped database copy"""

if not os.path.isdir(backupdir):
    raise Exception("Backup directory does not exist: {}".format(backupdir))

backup_file = r"E:\TESTING\BackUp.db" + time.strftime("-%Y%m%d-%H%M%S")

connection = sqlite3.connect(r"E:\TESTING\Accounts.db")
cursor = connection.cursor()

# Lock database before making a backup
cursor.execute('begin immediate')
# Make new backup file
shutil.copyfile(dbfile, backup_file)
print ("\nCreating {}...".format(backup_file))
# Unlock database
connection.rollback()

def clean_data(backup_dir):

backup_dir = r"E:\TESTING\BackUp.db"

print ("\n------------------------------")
print ("Cleaning up old backups")

for filename in os.listdir(backup_dir):
    backup_file = os.path.join(backup_dir, filename)
    if os.stat(backup_file).st_ctime < (time.time() - NO_OF_DAYS * 86400):
        if os.path.isfile(backup_file):
            os.remove(backup_file)
            print ("Deleting {}...".format(ibackup_file))

def get_arguments():
##    connection = sqlite3.connect(r"E:\TESTING\Accounts.db")
##    cursor = connection.cursor()
backup_dir = r"E:\TESTING\BackUp.db"
db_file = sqlite3.connect(r"E:\TESTING\Accounts.db")
"""Parse the commandline arguments from the user"""

parser = argparse.ArgumentParser()
parser.add_argument('db_file',
                    help='the database file that needs backed up')
parser.add_argument('backup_dir',
                     help='the directory where the backup'
                          'file should be saved')
return parser.parse_args()

if __name__ == "__main__":
#args = get_arguments()
dbfile = Accounts
backup_dir = "E:\TESTING"
#sqlite3_backup(args.db_file, args.backup_dir)
sqlite3_backup(db_file, backup_dir)
clean_data(args.backup_dir)

print ("\nBackup update has been successful.")

当我运行代码时,我收到此错误usage: backup.py [-h] db_file backup_dir backup.py: error: the following arguments are required: db_file, backup_dir

我已经在db_file和backup_dir中加入了代码,但它仍然出现了相同的错误。

1 个答案:

答案 0 :(得分:0)

您可能需要更改此部分:

if __name__ == "__main__":
    #args = get_arguments()
    dbfile = <<YOUR DB FILE NAME >>
    backup_dir = <<YOUR BACK UP DIRECTORY PATH>>
    #sqlite3_backup(args.db_file, args.backup_dir)
    sqlite3_backup(db_file, backup_dir)
    # CHANGE  clean_data(args.backup_dir)
    #TO: 
    clean_data(backup_dir)
    print ("\nBackup update has been successful.")