本文目录导读:

- 使用 SQLite3(Python 内置,无需安装)
- 使用 MySQL(需要安装 pymysql)
- 使用 PostgreSQL(需要安装 psycopg2)
- 使用 ORM(SQLAlchemy)— 推荐用于大型项目
- 最佳实践建议
在Python中新增数据库数据,最常见的方式是使用 SQLite3(内置) 或 MySQL/PostgreSQL(需要安装驱动),下面我会分别给出这些场景下的完整案例。
使用 SQLite3(Python 内置,无需安装)
适合轻量级单机应用,无需配置数据库服务器。
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
)
''')
# 3. 新增单条数据
cursor.execute('''
INSERT INTO users (name, age, email)
VALUES (?, ?, ?)
''', ('张三', 25, 'zhangsan@example.com'))
# 4. 新增多条数据
users_data = [
('李四', 30, 'lisi@example.com'),
('王五', 28, 'wangwu@example.com'),
('赵六', 35, 'zhaoliu@example.com')
]
cursor.executemany('''
INSERT INTO users (name, age, email)
VALUES (?, ?, ?)
''', users_data)
# 5. 提交事务
conn.commit()
print("数据添加成功!")
print(f"影响的行数:{cursor.rowcount}")
# 6. 查询验证
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
for row in rows:
print(row)
# 7. 关闭连接
cursor.close()
conn.close()
关键点说明:
- 参数化查询:使用 占位符,防止 SQL 注入
executemany():批量插入数据,性能更好commit():必须执行,否则数据不会真正写入数据库rowcount:获取影响的行数
使用 MySQL(需要安装 pymysql)
import pymysql
# 1. 连接数据库
connection = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
try:
with connection.cursor() as cursor:
# 2. 创建表(如果不存在)
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
department VARCHAR(50),
salary DECIMAL(10, 2),
hire_date DATE
)
''')
# 3. 新增单条数据
sql = "INSERT INTO employees (name, department, salary, hire_date) VALUES (%s, %s, %s, %s)"
cursor.execute(sql, ('John Doe', 'Engineering', 75000.00, '2024-01-15'))
# 4. 新增多条数据
employees_data = [
('Jane Smith', 'Marketing', 65000.00, '2024-02-01'),
('Bob Johnson', 'Sales', 70000.00, '2024-03-10'),
('Alice Brown', 'HR', 60000.00, '2024-04-20')
]
cursor.executemany(sql, employees_data)
# 5. 提交事务
connection.commit()
# 6. 获取自增ID
last_id = cursor.lastrowid
print(f"最后插入的ID: {last_id}")
finally:
connection.close()
安装 pymysql:
pip install pymysql
使用 PostgreSQL(需要安装 psycopg2)
import psycopg2
# 1. 连接数据库
conn = psycopg2.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
try:
cursor = conn.cursor()
# 2. 创建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
price NUMERIC(10, 2),
quantity INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 3. 新增单条数据
cursor.execute(
"INSERT INTO products (name, price, quantity) VALUES (%s, %s, %s)",
('Laptop', 999.99, 10)
)
# 4. 新增多条数据
products = [
('Mouse', 29.99, 50),
('Keyboard', 79.99, 30),
('Monitor', 299.99, 15)
]
# 使用 execute_values 批量插入(需要 psycopg2.extras)
from psycopg2.extras import execute_values
execute_values(
cursor,
"INSERT INTO products (name, price, quantity) VALUES %s",
products
)
# 5. 提交
conn.commit()
finally:
cursor.close()
conn.close()
安装 psycopg2:
pip install psycopg2-binary
使用 ORM(SQLAlchemy)— 推荐用于大型项目
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 1. 定义模型
Base = declarative_base()
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(100), nullable=False)
grade = Column(Float)
major = Column(String(50))
# 2. 连接数据库(这里用 SQLite 示例)
engine = create_engine('sqlite:///school.db', echo=True)
Base.metadata.create_all(engine)
# 3. 创建会话
Session = sessionmaker(bind=engine)
session = Session()
try:
# 4. 新增单条
student1 = Student(name='小明', grade=85.5, major='计算机科学')
session.add(student1)
# 5. 新增多条
students = [
Student(name='小红', grade=92.0, major='数学'),
Student(name='小刚', grade=78.5, major='物理'),
Student(name='小丽', grade=88.0, major='英语')
]
session.add_all(students)
# 6. 提交
session.commit()
print("数据插入成功!")
except Exception as e:
session.rollback()
print(f"错误:{e}")
finally:
session.close()
安装 SQLAlchemy:
pip install sqlalchemy
最佳实践建议
- 使用参数化查询:永远不要拼接 SQL 字符串,防止 SQL 注入攻击
- 批量操作:涉及多条数据时使用
executemany()或execute_values() - 异常处理:使用 try-except 块,必要时进行 rollback
- 连接管理:使用
with语句或确保在 finally 中关闭连接 - 事务管理:显式调用
commit()和rollback()
这些方法覆盖了从简单到复杂的场景,你可以根据自己的项目需求选择合适的方案,如果还有其他问题,欢迎继续提问!