跳過到頁腳內容
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標準如PDF/A和PDF/UA,支援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. 創建表格:

    • 定義一個SQLite表users,包含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)以釋放資源。

此腳本演示了從資料庫設置到資料操作和PDF生成的完整工作流程,使用Python的SQLite3和IronPDF庫。

輸出

sqlite3 Python(對開發者如何運作):圖2 - 示例控制檯輸出

PDF

sqlite3 Python(對開發者如何運作):圖3 - 由IronPDF生成的示例PDF輸出,使用sqlite查詢數據

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
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。