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()建立表格
使用 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
)
''')插入數據
以下是如何向資料庫表中插入資料:
# 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()查詢數據
您可以執行 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)更新數據
更新表中的現有資料:
# 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()刪除數據
若要從資料庫中刪除名稱為 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()關閉連接
完成後,請務必關閉遊標和連線:
# Close the cursor and connection
cur.close()
conn.close()# Close the cursor and connection
cur.close()
conn.close()進階功能
使用上下文管理器
您可以使用上下文管理器來自動處理連線關閉:
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)處理交易
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}")IronPDF簡介

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 程式示範如何使用 SQLite 庫建立資料庫、向其中插入資料、執行查詢、更新記錄、刪除記錄,並最終使用IronPDF產生 PDF 文件。
1.導入庫:
sqlite3: Python 內建的處理 SQLite 資料庫的模組。ironpdf: 從IronPDF導入元件,從而產生 PDF。
2.連接資料庫:
- 建立與名為
example.db的 SQLite 資料庫的連線。
3.建立表格:
- 定義一個 SQLite 表
users,其中包含列id(INTEGER, PRIMARY KEY)、name(TEXT, NOT NULL) 和age(INTEGER)。
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 生成的完整工作流程。
輸出


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";結論

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










