跳至頁尾內容
PYTHON 幫助

sqlite3 Python(開發者使用指南)

Python 中的sqlite3模組提供了一種與 SQLite 資料庫互動的方法。 它是 Python 標準庫的一部分,因此您無需額外安裝任何內容即可使用它。 讓我們來探索它的功能並看一些程式碼範例。 本文稍後將探討 IronPDF,這是一個由 Iron Software 開發的 PDF 產生庫。

SQLite 是一個輕量級的、基於磁碟的資料庫,不需要單獨的資料庫伺服器程序。 sqlite3 模組提供了一個符合 SQL 介面的環境,可以與現有資料庫或新建立的資料庫無縫互動。 此模組強制執行 PEP 249 中所述的 DB-API 2.0 規格。

基本用法

這裡提供一個簡單的範例和多個 SQL 語句,幫助您開始使用sqlite3

連接到資料庫

首先,你需要連接到你的 SQLite 資料庫。 如果資料庫檔案缺失,則會產生該檔案:

import sqlite3

# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor object
cur = conn.cursor()
import sqlite3

# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor object
cur = conn.cursor()
PYTHON

建立表格

使用 CREATE TABLE SQL 語句建立新的資料表:

# Create a table using SQL statements
cur.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        age INTEGER
    )
''')
# Create a table using SQL statements
cur.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        age INTEGER
    )
''')
PYTHON

插入數據

以下是如何向資料庫表中插入資料:

# Insert data into the table
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('Alice', 30))

# Commit the transaction using the connection object
conn.commit()
# Insert data into the table
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('Alice', 30))

# Commit the transaction using the connection object
conn.commit()
PYTHON

查詢數據

您可以執行 SQL 命令並從資料庫表中取得結果:

# Query the database
cur.execute('SELECT * FROM users')

# Fetch all results
rows = cur.fetchall()

# Print the results
for row in rows:
    print(row)
# Query the database
cur.execute('SELECT * FROM users')

# Fetch all results
rows = cur.fetchall()

# Print the results
for row in rows:
    print(row)
PYTHON

更新數據

更新表中的現有資料:

# Update data in the table
cur.execute('''
    UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))

# Commit the transaction
conn.commit()
# Update data in the table
cur.execute('''
    UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))

# Commit the transaction
conn.commit()
PYTHON

刪除數據

若要從資料庫中刪除名稱為 Alice 的行資料:

# Delete data from the table
cur.execute('''
    DELETE FROM users WHERE name = ?
''', ('Alice',))

# Commit the transaction
conn.commit()
# Delete data from the table
cur.execute('''
    DELETE FROM users WHERE name = ?
''', ('Alice',))

# Commit the transaction
conn.commit()
PYTHON

關閉連接

完成後,請務必關閉遊標和連線:

# Close the cursor and connection
cur.close()
conn.close()
# Close the cursor and connection
cur.close()
conn.close()
PYTHON

進階功能

使用上下文管理器

您可以使用上下文管理器來自動處理連線關閉:

with sqlite3.connect('example.db') as conn:
    cur = conn.cursor()
    cur.execute('SELECT * FROM users')
    rows = cur.fetchall()
    for row in rows:
        print(row)
with sqlite3.connect('example.db') as conn:
    cur = conn.cursor()
    cur.execute('SELECT * FROM users')
    rows = cur.fetchall()
    for row in rows:
        print(row)
PYTHON

處理交易

SQLite 支援事務,您可以使用 BEGIN、COMMIT 和 ROLLBACK 來管理它們:

try:
    conn.execute('BEGIN')
    cur.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Bob', 25))
    conn.commit()
except sqlite3.Error as e:
    conn.rollback()
    print(f"An error occurred: {e}")
try:
    conn.execute('BEGIN')
    cur.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Bob', 25))
    conn.commit()
except sqlite3.Error as e:
    conn.rollback()
    print(f"An error occurred: {e}")
PYTHON

介紹 IronPDF。

! sqlite3 Python(開發者使用指南):圖 1 - IronPDF:Python PDF 庫

IronPDF是一個功能強大的 Python 庫,旨在利用 HTML、CSS、圖像和 JavaScript 創建、編輯和簽署 PDF 文件。 它提供商業級的效能與低記憶體佔用量。 主要功能包括

HTML 轉 PDF:

將 HTML 檔案、HTML 字串和 URL 轉換為 PDF。 例如,使用 Chrome PDF 渲染器將網頁渲染為 PDF。

跨平台支援:

與各種 .NET 平台相容,包括 .NET Core、.NET Standard 和 .NET Framework。 它支援 Windows、Linux 和 macOS。

編輯和簽署:

設定屬性、透過密碼和權限增加安全性,並將數位簽章套用至 PDF。

頁面範本和設定:

使用頁眉、頁腳、頁碼和可調整的邊距自訂 PDF。 它支援響應式佈局和自訂紙張尺寸。

標準符合性:

它符合 PDF/A 和 PDF/UA 等 PDF 標準,支援 UTF-8 字元編碼,並管理圖像、CSS 和字體等資源。

使用 IronPDF 和 SQLite3 Python 產生 PDF 文件

import sqlite3
from ironpdf import * 

# Apply your license key
License.LicenseKey = "key"

# Connect to the sqlite database file (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')

# Create a cursor object for database connection
cur = conn.cursor()

# Create a table SQL command 
cur.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        age INTEGER
    )
''')

# Insert data into the table
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser1', 30))
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser2', 31))
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser3', 25))
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser4', 28))

# Commit the transaction using the connection object
conn.commit()

# Query the database
cur.execute('SELECT * FROM users')

# Fetch all results
rows = cur.fetchall()

# Print the results
for row in rows:
    print(row)

# Update data in the table
cur.execute('''
    UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))

# Commit the transaction
conn.commit()    

# Delete data from the table
cur.execute('''
    DELETE FROM users WHERE name = ?
''', ('IronUser1',))

# Commit the transaction
conn.commit()

# Initialize PDF renderer
renderer = ChromePdfRenderer()

# Create a PDF from an HTML string using Python
content = "<h1>Awesome Iron PDF with Sqlite3</h1>"
content += "<p>table data</p>"

for row in rows:
    content += "<p>" + str(row) + "</p>"

# Close the cursor and connection
cur.close()
conn.close()

# Render the HTML as a PDF
pdf = renderer.RenderHtmlAsPdf(content)

# Export to a file
pdf.SaveAs("DemoSqlite3.pdf")
import sqlite3
from ironpdf import * 

# Apply your license key
License.LicenseKey = "key"

# Connect to the sqlite database file (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')

# Create a cursor object for database connection
cur = conn.cursor()

# Create a table SQL command 
cur.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        age INTEGER
    )
''')

# Insert data into the table
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser1', 30))
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser2', 31))
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser3', 25))
cur.execute('''
    INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser4', 28))

# Commit the transaction using the connection object
conn.commit()

# Query the database
cur.execute('SELECT * FROM users')

# Fetch all results
rows = cur.fetchall()

# Print the results
for row in rows:
    print(row)

# Update data in the table
cur.execute('''
    UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))

# Commit the transaction
conn.commit()    

# Delete data from the table
cur.execute('''
    DELETE FROM users WHERE name = ?
''', ('IronUser1',))

# Commit the transaction
conn.commit()

# Initialize PDF renderer
renderer = ChromePdfRenderer()

# Create a PDF from an HTML string using Python
content = "<h1>Awesome Iron PDF with Sqlite3</h1>"
content += "<p>table data</p>"

for row in rows:
    content += "<p>" + str(row) + "</p>"

# Close the cursor and connection
cur.close()
conn.close()

# Render the HTML as a PDF
pdf = renderer.RenderHtmlAsPdf(content)

# Export to a file
pdf.SaveAs("DemoSqlite3.pdf")
PYTHON

程式碼解釋

本 Python 程式示範如何使用 SQLite 程式庫建立資料庫、在其中插入資料、執行查詢、更新記錄、刪除記錄,並最終使用 IronPDF 產生 PDF 文件。

1.導入庫:

  • sqlite3 :Python 內建的用於處理 SQLite 資料庫的模組。
  • ironpdf :從 IronPDF 匯入元件,從而產生 PDF 檔案。

2.連接資料庫:

  • 建立與名為example.db的 SQLite 資料庫的連線。

3.建立表格:

  • 定義一個users SQLite 表,包含id (整數,主鍵)、 name (文本,非空)和age (整數)列。

4.插入資料:

  • users表中插入多行資料。

5.提交交易:

  • 將變更提交至資料庫,使其永久儲存。

6.查詢資料庫:

  • 執行 SELECT 語句,從users表中擷取所有行。

7.更新數據:

  • 更新名為"Alice"的用戶的age

8.刪除數據:

  • users表中刪除名為"IronUser1"的使用者。

9.生成 PDF:

  • 使用 IronPDF( ChromePdfRenderer )從 HTML 內容建立 PDF 文件。
  • 將標題和表格資料(從資料庫檢索)合併到 HTML 內容中。
  • 將 PDF 文件另存為DemoSqlite3.pdf

10.結束聯繫:

  • 關閉遊標( cur )和連線( conn )以釋放資源。

這個腳本示範了使用 Python 的 SQLite3 和 IronPDF 庫,從資料庫設定到資料處理和 PDF 生成的完整工作流程。

輸出

! sqlite3 Python(開發者使用指南):圖 2 - 控制台輸出範例

PDF

! sqlite3 Python(開發者使用指南):圖 3 - 使用 sqlite 查詢數據,從 IronPDF 產生的 PDF 輸出範例

IronPDF 授權。

IronPDF需要許可證密鑰才能運作。 IronPDF for Python 提供免費試用許可證金鑰,使用戶能夠在購買前測試其豐富的功能。

請在此輸入許可證密鑰:

import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

結論

! sqlite3 Python(開發者使用指南):圖 4 - IronPDF 許可頁面

sqlite3 模組是一個強大且易於使用的工具,用於在 Python 中處理 SQLite 資料庫。 它與 Python 標準庫的整合使得簡單和複雜的資料庫操作變得方便。 IronPDF提供試用許可證。 之後,許可證價格從$799起。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。