跳至页脚内容
PYTHON 帮助

sqlite3 Python(开发人员如何使用)

Python中的sqlite3模块提供了一种与SQLite数据库交互的方法。 它是Python标准库的一部分,因此您无需安装额外的东西即可使用它。 让我们探讨其功能并查看一些代码示例。 在本文后面,我们将探索由Iron Software开发的PDF生成库IronPDF。

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 简介

!

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(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的完整工作流程。

输出

!

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中SQLite数据库的工具。 它的集成到Python标准库中使简单和复杂的数据库操作变得方便。 IronPDF提供试用许可证。 之后,许可证起价为$799及以上。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。