当前位置: 代码网 > it编程>前端脚本>Python > Python中如何使用sqlite3操作SQLite数据库详解

Python中如何使用sqlite3操作SQLite数据库详解

2025年03月14日 Python 我要评论
前言在 python 开发中,sqlite是一种轻量级的关系型数据库,它无需单独安装数据库服务器,所有数据存储在一个单独的文件中,适用于小型应用、移动开发、数据分析等场景。python 提供了内置的s

前言

在 python 开发中,sqlite 是一种轻量级的关系型数据库,它无需单独安装数据库服务器,所有数据存储在一个单独的文件中,适用于小型应用、移动开发、数据分析等场景。python 提供了内置的 sqlite3 模块,方便我们操作 sqlite 数据库。本文将详细介绍 sqlite3 模块的使用,包括数据库连接、表操作、数据增删改查(crud),以及常见的事务管理参数化查询,帮助你快速掌握 python 操作 sqlite 数据库的方法。

1. 为什么选择 sqlite?

✅ 零配置:python 内置支持,无需安装额外数据库服务。

✅ 文件存储:数据库仅是一个 .db 文件,便于管理。

✅ 轻量高效:适用于小型应用、测试环境、移动端存储。

✅ sql 支持:支持 sql 语法,易于与其他数据库迁移。

📌 sqlite 适用场景

  • 桌面应用(如浏览器、记事本应用存储用户数据)。
  • 移动应用(android、ios 本地数据库)。
  • 数据分析(存储小型数据集,替代 csv 文件)。

2. 连接 sqlite 数据库

2.1 连接或创建数据库

使用 sqlite3.connect() 连接数据库:

import sqlite3

# 连接数据库(如果不存在则创建)
conn = sqlite3.connect("example.db")

print("数据库连接成功")

📌 特点

  • 如果 example.db 存在,则连接它,否则自动创建该文件。

2.2 获取游标(cursor)

数据库操作需要使用 游标对象(cursor)

cursor = conn.cursor()

📌 作用

  • cursor.execute(sql) 用于执行 sql 语句。
  • cursor.fetchall() 获取查询结果。

3. 创建表(create table)

使用 create table 语句创建数据库表:

cursor.execute('''
    create table if not exists users (
        id integer primary key autoincrement,
        name text not null,
        age integer,
        city text
    )
''')
conn.commit()  # 提交更改
print("表创建成功")

📌 解析

  • id integer primary key autoincrement:主键自增。
  • text not nullname 必须有值。
  • if not exists:避免重复创建表。

4. 插入数据(insert into)

4.1 插入单条数据

cursor.execute("insert into users (name, age, city) values (?, ?, ?)",
               ("alice", 25, "new york"))
conn.commit()
print("插入数据成功")

📌 注意

  • ? 占位符 避免 sql 注入。
  • conn.commit() 提交事务,否则数据不会保存。

4.2 插入多条数据(executemany())

users = [
    ("bob", 30, "san francisco"),
    ("charlie", 28, "los angeles"),
    ("david", 35, "seattle")
]

cursor.executemany("insert into users (name, age, city) values (?, ?, ?)", users)
conn.commit()
print("批量插入成功")

📌 适用于

  • 批量写入数据,避免多次 execute() 提高效率。

5. 查询数据(select)

5.1 查询所有数据

cursor.execute("select * from users")
rows = cursor.fetchall()

for row in rows:
    print(row)

📌 fetchall() 获取所有数据,返回列表

(1, 'alice', 25, 'new york')
(2, 'bob', 30, 'san francisco')
(3, 'charlie', 28, 'los angeles')

5.2 查询单条数据(fetchone())

cursor.execute("select * from users where name = ?", ("alice",))
user = cursor.fetchone()
print(user)

📌 fetchone() 获取单条数据,适用于查询唯一记录

6. 更新数据(update)

cursor.execute("update users set age = ? where name = ?", (26, "alice"))
conn.commit()
print("数据更新成功")

📌 确保

  • set age = ? 只更新 age 列,避免误修改其他数据。

7. 删除数据(delete)

cursor.execute("delete from users where name = ?", ("david",))
conn.commit()
print("数据删除成功")

📌 务必小心

  • 没有 where 条件会删除所有数据
  • 先 select 确认数据是否存在。

8. 事务管理(commit() 和 rollback())

8.1 commit() 提交事务

conn.commit()  # 确保数据写入数据库

📌 每次 insert、update、delete 后,都要 commit() 确保数据持久化

8.2 rollback() 回滚事务

try:
    cursor.execute("update users set age = ? where name = ?", (100, "charlie"))
    raise exception("模拟异常")  # 模拟错误
    conn.commit()
except exception as e:
    conn.rollback()  # 发生错误时回滚
    print("事务回滚:", e)

📌 作用

  • 如果操作失败,回滚到上一次 commit(),防止错误影响数据库。

9. 关闭数据库连接

cursor.close()
conn.close()
print("数据库连接已关闭")

📌 最佳实践

  • 完成所有数据库操作后,应关闭连接,释放资源。

10. 结合 with 语句自动管理连接

python 提供 with 语法,自动关闭数据库连接

with sqlite3.connect("example.db") as conn:
    cursor = conn.cursor()
    cursor.execute("select * from users")
    print(cursor.fetchall())

📌 优势

  • 自动 commit()
  • 异常发生时自动 rollback()
  • 退出时自动关闭 conn

11. 使用 row 以字典方式访问数据

默认 fetchall() 返回元组

cursor.execute("select * from users")
print(cursor.fetchone())  # (1, 'alice', 25, 'new york')

可以改用 sqlite3.row 使数据可用字典访问

conn.row_factory = sqlite3.row  # 设置行工厂
cursor = conn.cursor()

cursor.execute("select * from users")
row = cursor.fetchone()
print(row["name"], row["age"])  # alice 25

📌 适用于

  • 提高可读性,避免 row[0] 这样的索引访问方式。

12. 结论

操作代码示例
连接数据库conn = sqlite3.connect("example.db")
创建表create table users (id integer primary key, name text, age integer)
插入数据insert into users (name, age) values (?, ?)
查询数据select * from users
更新数据update users set age = ? where name = ?
删除数据delete from users where name = ?
事务管理commit() / rollback()
关闭连接conn.close()

sqlite3 是 python 内置的数据库模块,适用于小型应用、测试、数据存储等场景。掌握这些操作,你就可以轻松管理 sqlite 数据库,提升开发效率!

总结

到此这篇关于python中如何使用sqlite3操作sqlite数据库的文章就介绍到这了,更多相关python sqlite3操作sqlite内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com