下面我将为你提供一个从零开始的详细指南,包括如何创建数据库、表、插入数据、查询数据以及最佳实践。
核心概念
- 数据库: 在 SQLite 中,一个数据库就是一个单独的文件(
mydatabase.db),如果这个文件不存在,sqlite3模块在连接时会自动创建它。 - 连接: 你需要一个
Connection对象来与数据库文件进行交互,这个对象代表了你的数据库会话。 - 游标: 你需要一个
Cursor对象来执行 SQL 语句(如CREATE,INSERT,SELECT等),游标允许你遍历查询结果集。 - 提交: 当你执行了修改数据库的操作(如
INSERT,UPDATE,DELETE)后,必须调用connection.commit()来将更改永久保存到数据库文件中。 - 关闭: 操作完成后,应该关闭游标和连接,以释放资源。
步骤 1: 创建数据库和连接
这是第一步,我们只需要尝试连接到一个不存在的数据库文件,SQLite 就会自动为我们创建它。
import sqlite3
# 数据库文件名
db_file = "mydatabase.db"
# try-except 块可以处理文件可能不存在的情况,但在这里它主要用来展示连接过程
try:
# 1. 创建连接
# mydatabase.db 文件不存在,sqlite3 会自动创建它
# 如果文件已存在,则打开该文件
conn = sqlite3.connect(db_file)
print(f"成功连接到数据库 '{db_file}'")
# 2. 创建一个游标对象
cursor = conn.cursor()
# 3. (可选)验证数据库版本
print(f"SQLite 版本: {sqlite3.sqlite_version}")
except sqlite3.Error as e:
print(f"数据库错误: {e}")
finally:
# 4. 关闭连接
# 这是一个好习惯,确保在任何情况下(即使发生错误)连接都会被关闭
if conn:
conn.close()
print("数据库连接已关闭。")
运行结果:
成功连接到数据库 'mydatabase.db'
SQLite 版本: 3.41.2
数据库连接已关闭。
运行这段代码后,你的项目目录下会出现一个新的文件 mydatabase.db。
步骤 2: 创建表
连接到数据库后,我们可以使用 CREATE TABLE 语句来创建表,最佳实践是使用 try-except 来处理可能存在的表已错误。
import sqlite3
db_file = "mydatabase.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# 定义创建表的 SQL 语句
# 使用 IF NOT EXISTS 可以防止在表已存在时出错
create_table_sql = """
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
age INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
# 执行 SQL 语句
cursor.execute(create_table_sql)
# 提交更改
conn.commit()
print("表 'users' 创建成功或已存在。")
except sqlite3.Error as e:
print(f"数据库错误: {e}")
finally:
if conn:
conn.close()
说明:
CREATE TABLE IF NOT EXISTS users (...):users表不存在,就创建它,如果已存在,则忽略此语句,避免报错。id INTEGER PRIMARY KEY AUTOINCREMENT:id是主键,INTEGER类型,AUTOINCREMENT会自动为每条新记录生成一个唯一的递增编号。name TEXT NOT NULL:name列是文本类型,且不能为空。email TEXT NOT NULL UNIQUE:email列不能为空,并且所有值必须是唯一的。created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP: 记录创建时,此列会自动填充当前时间戳。conn.commit(): 非常重要! 没有它,表不会被实际创建。
步骤 3: 插入数据
使用 INSERT INTO 语句向表中添加数据。
import sqlite3
from datetime import datetime
db_file = "mydatabase.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# 插入单条记录
insert_sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)"
user_data = ("Alice", "alice@example.com", 30)
cursor.execute(insert_sql, user_data)
# 插入另一条记录
user_data_2 = ("Bob", "bob@example.com", 25)
cursor.execute(insert_sql, user_data_2)
# 提交事务
conn.commit()
print(f"成功插入 {cursor.rowcount} 条记录。") # cursor.rowcount 显示受影响的行数
except sqlite3.Error as e:
print(f"数据库错误: {e}")
finally:
if conn:
conn.close()
重要提示: 使用 作为占位符
- 永远不要使用 Python 的字符串格式化(如
f"INSERT ... VALUES ({name}, ...)")来构建 SQL 查询,这会导致 SQL 注入 安全漏洞。 sqlite3模块使用 作为参数化查询的占位符,它会自动处理数据的转义,确保数据被安全地插入到 SQL 语句中。
步骤 4: 查询数据
使用 SELECT 语句从表中检索数据。
import sqlite3
db_file = "mydatabase.db"
try:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# 查询所有用户
select_sql = "SELECT id, name, email, age, created_at FROM users"
cursor.execute(select_sql)
# 获取所有查询结果
all_users = cursor.fetchall()
print("--- 所有用户 ---")
for user in all_users:
print(f"ID: {user[0]}, 姓名: {user[1]}, 邮箱: {user[2]}, 年龄: {user[3]}, 创建时间: {user[4]}")
# 查询特定条件的用户 (例如年龄大于28的用户)
select_where_sql = "SELECT name, email FROM users WHERE age > ?"
cursor.execute(select_where_sql, (28,)) # 注意这里的元组 (28,)
older_users = cursor.fetchall()
print("\n--- 年龄大于28的用户 ---")
for user in older_users:
print(f"姓名: {user[0]}, 邮箱: {user[1]}")
except sqlite3.Error as e:
print(f"数据库错误: {e}")
finally:
if conn:
conn.close()
查询方法:
cursor.fetchall(): 获取查询结果集中的所有行,返回一个元组列表。cursor.fetchone(): 获取下一行,返回一个元组,如果结果集为空,则返回None。cursor.fetchmany(size): 获取指定数量的行。
完整示例 (使用 with 语句)
为了使代码更简洁、更安全(自动处理连接的关闭),Python 的 sqlite3 模块支持上下文管理器(with 语句),这是目前推荐的写法。
import sqlite3
from datetime import datetime
def main():
db_file = "mydatabase.db"
# --- 1. 创建表 ---
try:
with sqlite3.connect(db_file) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_name TEXT NOT NULL,
price REAL NOT NULL,
stock INTEGER DEFAULT 0
);
""")
print("表 'products' 创建成功。")
except sqlite3.Error as e:
print(f"创建表时出错: {e}")
# --- 2. 插入数据 ---
products_to_add = [
("Laptop", 999.99, 50),
("Mouse", 25.50, 200),
("Keyboard", 75.00, 150)
]
try:
with sqlite3.connect(db_file) as conn:
cursor = conn.cursor()
insert_sql = "INSERT INTO products (product_name, price, stock) VALUES (?, ?, ?)"
# executemany 可以高效地插入多条数据
cursor.executemany(insert_sql, products_to_add)
conn.commit()
print(f"成功插入 {cursor.rowcount} 条产品记录。")
except sqlite3.Error as e:
print(f"插入数据时出错: {e}")
# --- 3. 查询数据 ---
try:
with sqlite3.connect(db_file) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM products")
# 使用 row_factory 可以将结果映射为字典,更易读
conn.row_factory = sqlite3.Row
cursor = conn.cursor() # 重新获取一个使用新 factory 的 cursor
print("\n--- 产品列表 ---")
for row in cursor:
# 现在可以通过列名访问数据
print(f"ID: {row['id']}, 产品: {row['product_name']}, 价格: ${row['price']:.2f}, 库存: {row['stock']}")
except sqlite3.Error as e:
print(f"查询数据时出错: {e}")
if __name__ == "__main__":
main()
- 导入:
import sqlite3 - 连接:
conn = sqlite3.connect("your_database.db")(文件不存在则自动创建) - 游标:
cursor = conn.cursor() - 执行SQL:
cursor.execute("YOUR SQL QUERY", (param1, param2))(始终用 占位符) - 提交:
conn.commit()(用于INSERT,UPDATE,DELETE) - 查询:
results = cursor.fetchall()或cursor.fetchone() - 关闭:
conn.close()(或使用with语句自动管理)
遵循这些步骤,你就可以在 Python 中轻松地使用 sqlite3 来创建和管理你的本地数据库了。
