有什么方法可以在python中备份sqlite db?

q5iwbnjs  于 2023-05-18  发布在  SQLite
关注(0)|答案(2)|浏览(226)

我使用sqlite3存储我的电报机器人的用户,每次当我部署或运行我的机器人我的数据库重新启动,并插入一些数据后,我试图复制数据库文件,但我仍然有旧的数据,这里是我的代码
我已经尝试使用备份方法,但它是不工作或太慢

connection = sqlite3.connect('users.db')

def backup(conn):
    new_db = sqlite3.connect('users.db')
    conn.backup(new_db)
    new_db.close()

backup(connection)

机器人代码

connection = sqlite3.connect('users.db')
cursor = connection.cursor()
cursor.execute(
    'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, chat_id INTEGER, name VARCHAR(255))')

@dp.message_handler(commands=['start'])
async def send_welcome(message: Message):
    chat_id = message.chat.id
    user_name = message.from_user.first_name
    users = cursor.execute('SELECT count(chat_id) FROM users WHERE chat_id = :chat_id', {'chat_id': chat_id})
    is_user = list(users.fetchall()[0])[0]
    if not is_user:
        cursor.execute("INSERT INTO  users (id, chat_id, name)  VALUES (NULL, ?, ?)", (chat_id, user_name))
        connection.commit()
    connection.close()
    await bot.send_message(chat_id, f'Hello {user_name}, this bot helps you to download media files from '
                                    f'social medias such as *tiktok, instagram, youtube, pinterest*',
                           'markdownv2')



admins = [679679313]

@dp.message_handler(commands=['stat'])
async def send_message(message: Message):
    chat_id = message.chat.id
    x = datetime.now()
    date = x.strftime("%B %d, %Y %H:%M:%S")
    users = cursor.execute('SELECT count(*) FROM users')
    if chat_id in admins:
        await bot.send_message(chat_id, f"""🤖Bot Statistics
👤 Users : {users.fetchall()[0][0]}
🗓️ {date}""")

@dp.message_handler(commands=['backup'])
async def send_message(message: Message):
    chat_id = message.chat.id
    if chat_id in admins:
        await bot.send_document(chat_id, open('users.db', "rb"))
hxzsmxv2

hxzsmxv21#

由于.db只是一个文件,您可以使用python和import os来复制该文件。

相关问题