如何使用 Python 创建 SQLite 数据库备份?


SQLite 是一种流行的轻量级无服务器数据库管理系统,广泛应用于许多应用程序。它以易用性、占用空间小和可移植性而闻名。但是,与任何其他数据库一样,为 SQLite 数据库创建备份以防止数据丢失非常重要。

Python 是一种功能强大的编程语言,广泛用于各种任务,包括数据处理和管理。在本教程中,我们将探讨如何使用 Python 创建 SQLite 数据库的备份。我们将逐步介绍连接到 SQLite 数据库、创建备份文件以及验证备份是否成功的过程。

本教程假设您具备 Python 和 SQLite 的基本知识。

我们的第一步是确保 SQLite3 已安装在我们的机器上,并且要检查这一点,我们可以运行以下命令。

sqlite3 

如果您获得类似于下面所示的系统,则可以继续执行以下示例。

SQLite version 3.39.5 2022-10-14 20:58:05
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> 

现在让我们举几个例子来说明如何创建 SQLite 数据库的备份。

示例 1:在 SQLite 中创建简单的数据库

在第一个示例中,我们将了解如何在 python 中使用 SQLite 创建简单的数据库。请考虑以下代码。

此代码定义了一个名为connect_to_database 的函数,该函数建立到名为mydatabase.db 的 SQLite 数据库的连接。

  • 如果连接成功建立,则该函数打印一条消息以确认此操作,并打印一条消息以确认数据库文件已创建。

  • 如果发生错误,则该函数打印错误消息。

该函数在代码末尾被调用以建立到数据库的连接,然后关闭连接。

# Import the required modules
import sqlite3
from sqlite3 import Error

# Define a function to establish a connection to the database
def connect_to_database():
   try:

      # Connect to the SQLite database
      conn = sqlite3.connect('mydatabase.db')
      
      # Print a message to confirm that the connection was established successfully
      print("Connection established successfully!")
      
      # Print a message to confirm that the database file has been created
      print("'mydatabase.db' created")
      
      # Return the connection object
      return conn
   except Error as e:
   
      # If an error occurs, print the error message
      print(e)

# Call the function to establish a connection to the database
conn = connect_to_database()

# Close the connection to the database
conn.close()

输出

执行此代码后,它将在同一文件夹中创建一个名为mydatabase.db 的新文件。

Connection established successfully!
'mydatabase.db' created

作为参考,现在我的当前目录如下所示 -

.
├── main.py
└── mydatabase.db
0 directories, 2 files 

示例 2:在 SQLite 数据库中创建表

现在作为下一步,假设我们想在我们的数据库中创建一个表。请考虑以下代码。

该代码连接到名为“mydatabase.db”的 SQLite 数据库,并在数据库中创建一个名为“students”的表,其中包含六列。

# Import the required modules
import sqlite3
from sqlite3 import Error

# Define a function to establish a connection to the database
def connect_to_database():
   try:
   
      # Connect to the SQLite database named mydatabase.db
      conn = sqlite3.connect('mydatabase.db')
      
      # Return the connection object
      return conn
   except Error as e:

      # If an error occurs, print the error message
      print(e)
      
# Define a function to create a table in the database
def create_table(conn):
   
   # Create a cursor object to execute SQL queries
   cursor = conn.cursor()
   
   # Define the SQL query to create a table named 'students'
   sql_query = '''CREATE TABLE students (
      roll_no INTEGER PRIMARY KEY,
      first_name TEXT,
      last_name TEXT,
      class TEXT,
      stream TEXT,
      address TEXT
   );'''
   
   # Execute the SQL query to create the table
   cursor.execute(sql_query)
   
   # Commit the changes to the database
   conn.commit()
   
   # Print a message to confirm that the table has been created
   print("Table 'students' created successfully") 
   
# Call the function to establish a connection to the database
conn = connect_to_database()

# Call the function to create a table in the database
create_table(conn)

# Close the connection to the database
conn.close() 

输出

执行后,您将获得以下输出 -

Table 'students' created successfully 

示例 3:创建数据库备份

现在让我们关注我们将创建当前数据库备份的代码。请考虑以下代码。

import sqlite3
import io
conn = sqlite3.connect('mydatabase.db')

# Open() function
with io.open('mydatabase_dump.sql', 'w') as p:

   # iterdump() function
   for line in conn.iterdump():
      p.write('%s\n' % line)
print(' Backup performed successfully!')
print(' Data Saved as backupdatabase_dump.sql')
conn.close() 

输出

执行后,您将获得以下输出 -

Backup performed successfully!
Data Saved as backupdatabase_dump.sql

此外,将创建一个新的 SQL 备份数据库。现在目录结构将如下所示 -

.
├── main.py
├── mydatabase.db
└── mydatabase_dump.sql
0 directories, 3 files 

结论

您可以使用 Python 创建 SQLite 数据库的备份,方法是打开数据库连接,使用 iterdump() 函数迭代数据,并使用 open() 函数将数据写入备份文件。此过程确保在数据丢失或损坏的情况下保存数据库的副本。

更新于: 2023年4月20日

2K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.