1. 连接到数据库
在 python 中使用 sqlite3.connect() 方法连接到 sqlite 数据库。如果数据库文件不存在,会自动创建。
import sqlite3
# 连接到数据库文件(如果不存在则自动创建)
conn = sqlite3.connect('example.db')- 解释:
connect('example.db'):创建或打开名为example.db的数据库文件。- 返回的
conn是数据库连接对象,后续操作都需要通过它进行。
2. 创建游标对象
通过连接对象创建游标(cursor),用于执行 sql 语句。
cursor = conn.cursor()
- 解释:
- 游标对象
cursor用于执行create table、insert into、select等 sql 语句。
- 游标对象
3. 创建表
使用 create table 语句创建表,推荐使用 if not exists 避免重复创建。
cursor.execute('''
create table if not exists users (
id integer primary key autoincrement,
name text not null,
age integer,
email text unique
)
''')
conn.commit()- 解释:
create table if not exists users:如果表users不存在则创建。id integer primary key autoincrement:id是主键,自动递增。name text not null:name字段为文本类型且不能为空。email text unique:email字段必须唯一。conn.commit():提交事务(必须执行,否则表不会被创建)。
4. 插入数据
使用 insert into 插入数据,推荐使用参数化查询防止 sql 注入。
# 单条插入
cursor.execute("insert into users (name, age, email) values (?, ?, ?)",
('alice', 25, 'alice@example.com'))
# 多条插入
users_data = [
('bob', 30, 'bob@example.com'),
('charlie', 35, 'charlie@example.com')
]
cursor.executemany("insert into users (name, age, email) values (?, ?, ?)", users_data)
conn.commit()- 解释:
values (?, ?, ?):?是占位符,python 会自动替换参数(防止 sql 注入)。executemany可一次插入多条数据。conn.commit()提交事务(插入操作必须提交)。
5. 查询数据
使用 select 查询数据,结果通过 fetchone() 或 fetchall() 获取。
# 查询所有用户
cursor.execute("select * from users")
rows = cursor.fetchall()
for row in rows:
print(row)
# 条件查询
cursor.execute("select name, age from users where age > ?", (30,))
result = cursor.fetchone()
print(result)- 解释:
select * from users:查询users表的所有字段。fetchall():获取所有查询结果(返回列表)。fetchone():获取单条结果(返回元组)。where age > ?:筛选age大于指定值的记录。
6. 更新数据
使用 update 修改已有数据。
cursor.execute("update users set age = ? where name = ?", (26, 'alice'))
conn.commit()- 解释:
set age = ?:将age字段更新为新值。where name = ?:仅更新name为'alice'的记录。conn.commit()提交事务。
7. 删除数据
使用 delete from 删除数据。
cursor.execute("delete from users where name = 'bob'")
conn.commit()- 解释:
delete from users:删除users表中的记录。where name = 'bob':仅删除name为'bob'的记录。conn.commit()提交事务。
8. 创建索引(可选)
索引可以加速查询,但会降低插入/更新速度。
cursor.execute("create index idx_name on users (name)")
conn.commit()- 解释:
create index idx_name on users (name):为users表的name字段创建索引。
9. 事务处理
sqlite 支持事务(begin, commit, rollback),确保操作的原子性。
try:
# 开始事务
conn.execute("begin")
# 执行多条操作
cursor.execute("insert into users (name, age) values (?, ?)", ('david', 28))
cursor.execute("update users set age = ? where name = ?", (29, 'david'))
# 提交事务
conn.commit()
except exception as e:
print("事务失败,回滚:", e)
conn.rollback() # 回滚事务- 解释:
begin:显式开始事务(默认情况下,每条语句都是独立事务)。conn.commit():提交事务(所有操作生效)。conn.rollback():回滚事务(撤销所有未提交的操作)。
10. 关闭连接
操作完成后,关闭游标和数据库连接。
cursor.close() conn.close()
- 解释:
- 关闭游标和连接释放资源,避免内存泄漏。
完整示例代码
import sqlite3
# 1. 连接数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 2. 创建表
cursor.execute('''
create table if not exists users (
id integer primary key autoincrement,
name text not null,
age integer,
email text unique
)
''')
conn.commit()
# 3. 插入数据
cursor.execute("insert into users (name, age, email) values (?, ?, ?)",
('alice', 25, 'alice@example.com'))
conn.commit()
# 4. 查询数据
cursor.execute("select * from users")
rows = cursor.fetchall()
for row in rows:
print(row)
# 5. 更新数据
cursor.execute("update users set age = ? where name = ?", (26, 'alice'))
conn.commit()
# 6. 删除数据
cursor.execute("delete from users where name = 'alice'")
conn.commit()
# 7. 关闭连接
cursor.close()
conn.close()常见错误与避坑指南
忘记提交事务
- 错误:插入/更新/删除后未调用
conn.commit()。 - 修正:每次修改数据后必须调用
conn.commit()。
- 错误:插入/更新/删除后未调用
sql 注入风险
- 错误:直接拼接 sql 语句(如
f"insert into users values ({name})")。 - 修正:使用参数化查询(如
values (?, ?))。
- 错误:直接拼接 sql 语句(如
字段名与保留字冲突
- 错误:使用
order,group等保留字作为字段名。 - 修正:避免使用保留字,或用引号包裹字段名(如
"order")。
- 错误:使用
未关闭连接
- 错误:程序结束时未关闭
cursor和conn。 - 修正:使用
with上下文管理器自动关闭资源:with sqlite3.connect('example.db') as conn: cursor = conn.cursor() # 执行操作...
- 错误:程序结束时未关闭
总结
到此这篇关于python连接sqlite3简单用法的文章就介绍到这了,更多相关python连接sqlite3用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论