Python操作SQLite数据库

SQLite 是一种轻量级的数据库引擎,广泛用于嵌入式设备和小型应用程序。在Python中,SQLite 是一个流行的选择,因为它易于使用、快速、可靠,并且无需独立的服务器进程。本文将深入探讨如何使用 Python 操作 SQLite 数据库,包括创建数据库、表格、插入数据、查询数据等。

主要优点是sqlite在Python中使用通常是以文件的形式存在, 这减少了很多配置工作,主要用于小型项目的数据上传保存。

安装Sqlite3

在 Python 中,SQLite3 已经内置,无需额外安装。可以直接 import sqlite3 来使用它。

python 复制代码
import sqlite3

连接数据库

使用 connect() 函数连接到数据库,并返回一个 Connection 对象。

python 复制代码
conn = sqlite3.connect('example.db')

同样支持指定路径

python 复制代码
# 指定路径为 /path/to/your/database/example.db
conn = sqlite3.connect('/path/to/your/database/example.db')

创建表格

建表(如果已存在则报错)

python 复制代码
# 建表(如果已存在则报错)
create_table_sql = """
CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER
);
"""

conn.execute(create_table_sql)

建表(如果已存在则不做操作) 通常就使用这种方式

python 复制代码
# 建表(如果已存在则不做操作)
create_table_sql = """
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER
);
"""

conn.execute(create_table_sql)

增删改查

python 复制代码
# 插入数据
def insert_user(name, age):
    sql = "INSERT INTO users (name, age) VALUES (?, ?)"
    conn.execute(sql, (name, age))
    conn.commit()


# 删除数据
def delete_user(user_id):
    sql = "DELETE FROM users WHERE id = ?"
    conn.execute(sql, (user_id,))
    conn.commit()


# 更新数据
def update_user(user_id, new_name, new_age):
    sql = "UPDATE users SET name = ?, age = ? WHERE id = ?"
    conn.execute(sql, (new_name, new_age, user_id))
    conn.commit()


# 查询多个数据(返回list)
def fetch_users():
    sql = "SELECT * FROM users"
    return conn.execute(sql).fetchall()

# 查询一个数据
def fetch_users():
    sql = "SELECT * FROM users"
    return conn.execute(sql).fetchone()

# 查询指定数目数据(返回list)
def fetch_users():
    sql = "SELECT * FROM users"
    return conn.execute(sql).fetchmany(10) # 获取10行

综合案例

python 复制代码
import sqlite3

# 连接到 SQLite 数据库,如果不存在将会创建一个新的数据库
conn = sqlite3.connect('example.db')

# 创建表的 SQL 语句
create_table_sql = """
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER
);
"""

# 执行创建表的 SQL 语句
conn.execute(create_table_sql)


# 插入数据
def insert_user(name, age):
    sql = "INSERT INTO users (name, age) VALUES (?, ?)"
    conn.execute(sql, (name, age))
    conn.commit()


# 删除数据
def delete_user(user_id):
    sql = "DELETE FROM users WHERE id = ?"
    conn.execute(sql, (user_id,))
    conn.commit()


# 更新数据
def update_user(user_id, new_name, new_age):
    sql = "UPDATE users SET name = ?, age = ? WHERE id = ?"
    conn.execute(sql, (new_name, new_age, user_id))
    conn.commit()


# 查询数据
def fetch_users():
    sql = "SELECT * FROM users"
    return conn.execute(sql).fetchall()


# 插入一些示例数据
insert_user("Alice", 30)
insert_user("Bob", 25)

# 输出所有用户
print("All users:")
for user in fetch_users():
    print(user)

# 更新用户
update_user(1, "Alice Smith", 31)

# 输出所有用户
print("\nAll users after update:")
for user in fetch_users():
    print(user)

# 删除用户
delete_user(2)

# 输出所有用户
print("\nAll users after delete:")
for user in fetch_users():
    print(user)

# 关闭游标对象和数据库连接
conn.close()

运行结果

bash 复制代码
All users:
(1, 'Alice Smith', 31)
(2, 'Alice', 30)
(3, 'Bob', 25)

All users after update:
(1, 'Alice Smith', 31)
(2, 'Alice', 30)
(3, 'Bob', 25)

All users after delete:
(1, 'Alice Smith', 31)
(3, 'Bob', 25)
相关推荐
Elastic 中国社区官方博客15 分钟前
Elasticsearch:圣诞晚餐 BBQ - 图像识别
大数据·数据库·elasticsearch·搜索引擎·ai·全文检索
cui_win21 分钟前
Prometheus实战教程 - Redis 监控
数据库·redis·prometheus
38242782728 分钟前
python:输出JSON
前端·python·json
JIngJaneIL1 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
TG:@yunlaoda360 云老大1 小时前
华为云国际站代理商备份策略设置过程中遇到问题如何解决?
服务器·数据库·华为云
也许是_1 小时前
大模型应用技术之 详解 MCP 原理
人工智能·python
SelectDB1 小时前
Doris Catalog 已上线!性能提升 200x,全面优于 JDBC Catalog,跨集群查询迈入高性能分析时代
数据库·数据分析·apache
TAEHENGV1 小时前
进度跟踪模块 Cordova 与 OpenHarmony 混合开发实战
android·javascript·数据库
沙漠豪2 小时前
提取PDF发票信息的Python脚本
开发语言·python·pdf
神秘面具男032 小时前
MySQL 从基础到实践
数据库·mysql