如何使用 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.