Python 操作数据库

admin Python评论6字数 6250阅读模式
摘要

📌 适合人群:Python 初学者 / 想系统了解数据库操作的同学
📌 你将学到:SQLite / MySQL / PostgreSQL / MongoDB / Redis 的增删改查

不管你是写 Web 后端、做数据分析,还是写自动化脚本,操作数据库都是一项躲不开的技能。
市面上数据库五花八门,但 Python 操作它们的套路其实高度一致——连接 → 执行 → 关闭。
这篇文章用一个用户管理系统的案例,手把手带你跑通 Python 操作 5 种主流数据库,每种都配完整可运行的代码。

前置安装

# 本文涉及的所有库,一键安装
pip install pymysql      # MySQL
pip install psycopg2     # PostgreSQL
pip install pymongo      # MongoDB
pip install redis        # Redis
# SQLite 不用装,Python 自带

 文章源自网吧系统维护-https://www.58pxe.com/12969.html

一、SQLite — 零配置,自带数据库

SQLite 是 Python 自带 的轻量级数据库,不需要安装、不需要启动服务,一个文件就是一个数据库。适合本地开发、小工具、移动端。文章源自网吧系统维护-https://www.58pxe.com/12969.html

连接 & 创建表

import sqlite3

# 连接数据库(文件不存在会自动创建)
conn = sqlite3.connect('demo.db')
cursor = conn.cursor()

# 创建用户表
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER,
        city TEXT
    )
''')
conn.commit()
print("✅ SQLite 表创建成功")

增删改查(CRUD)

# ---------- 新增 ----------
cursor.execute("INSERT INTO users (name, age, city) VALUES (?, ?, ?)",
               ('张三', 25, '北京'))
cursor.execute("INSERT INTO users (name, age, city) VALUES (?, ?, ?)",
               ('李四', 30, '上海'))
cursor.executemany("INSERT INTO users (name, age, city) VALUES (?, ?, ?)", [
    ('王五', 28, '广州'),
    ('赵六', 22, '深圳'),
    ('孙七', 35, '杭州'),
])
conn.commit()
print("✅ 新增成功")

# ---------- 查询 ----------
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(f"  ID: {row[0]}, 姓名: {row[1]}, 年龄: {row[2]}, 城市: {row[3]}")

# ---------- 更新 ----------
cursor.execute("UPDATE users SET age = ? WHERE name = ?", (26, '张三'))
conn.commit()
print("✅ 更新成功")

# ---------- 删除 ----------
cursor.execute("DELETE FROM users WHERE name = ?", ('孙七',))
conn.commit()
print("✅ 删除成功")

# ---------- 关闭 ----------
cursor.close()
conn.close()
print("✅ SQLite 操作完成")

💡 注意:SQLite 的 ? 是占位符,用于防止 SQL 注入,永远不要用 f-string 拼接 SQL!文章源自网吧系统维护-https://www.58pxe.com/12969.html

二、MySQL — 最流行的关系型数据库

MySQL 是 Web 开发中使用最广泛的数据库。Python 通过 pymysql 连接。文章源自网吧系统维护-https://www.58pxe.com/12969.html

连接 & 创建表

import pymysql

# 连接 MySQL(需要先启动 MySQL 服务)
conn = pymysql.connect(
    host='localhost',      # 数据库地址
    port=3306,             # 端口
    user='root',           # 用户名
    password='123456',     # 密码
    database='testdb',     # 数据库名
    charset='utf8mb4'      # 编码
)
cursor = conn.cursor()

# 创建用户表
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50) NOT NULL,
        age INT,
        city VARCHAR(50)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
''')
conn.commit()
print("✅ MySQL 表创建成功")

增删改查

# ---------- 新增 ----------
sql = "INSERT INTO users (name, age, city) VALUES (%s, %s, %s)"
cursor.execute(sql, ('张三', 25, '北京'))
cursor.executemany(sql, [
    ('李四', 30, '上海'),
    ('王五', 28, '广州'),
    ('赵六', 22, '深圳'),
])
conn.commit()
print("✅ 新增成功")

# ---------- 查询 ----------
cursor.execute("SELECT * FROM users")
for row in cursor.fetchall():
    print(f"  ID: {row[0]}, 姓名: {row[1]}, 年龄: {row[2]}, 城市: {row[3]}")

# ---------- 更新 ----------
cursor.execute("UPDATE users SET age = %s WHERE name = %s", (26, '张三'))
conn.commit()
print("✅ 更新成功")

# ---------- 删除 ----------
cursor.execute("DELETE FROM users WHERE name = %s", ('赵六',))
conn.commit()
print("✅ 删除成功")

cursor.close()
conn.close()

💡 MySQL 的占位符是 %s,和 SQLite 的 ? 不同,别搞混了。文章源自网吧系统维护-https://www.58pxe.com/12969.html

三、PostgreSQL — 功能最强大的开源数据库

PostgreSQL 被称为"开源界的 Oracle",支持复杂查询、JSON、事务、地理信息等。文章源自网吧系统维护-https://www.58pxe.com/12969.html

连接 & 创建表

import psycopg2

# 连接 PostgreSQL
conn = psycopg2.connect(
    host='localhost',
    port=5432,
    user='postgres',
    password='123456',
    dbname='testdb'
)
cursor = conn.cursor()

# 创建用户表
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id SERIAL PRIMARY KEY,
        name VARCHAR(50) NOT NULL,
        age INTEGER,
        city VARCHAR(50)
    )
''')
conn.commit()
print("✅ PostgreSQL 表创建成功")

增删改查

# ---------- 新增 ----------
sql = "INSERT INTO users (name, age, city) VALUES (%s, %s, %s)"
cursor.execute(sql, ('张三', 25, '北京'))
cursor.executemany(sql, [
    ('李四', 30, '上海'),
    ('王五', 28, '广州'),
])
conn.commit()
print("✅ 新增成功")

# ---------- 查询(带条件)----------
cursor.execute("SELECT * FROM users WHERE city = %s", ('上海',))
for row in cursor.fetchall():
    print(f"  ID: {row[0]}, 姓名: {row[1]}, 年龄: {row[2]}, 城市: {row[3]}")

# ---------- 更新 ----------
cursor.execute("UPDATE users SET age = %s WHERE name = %s", (31, '李四'))
conn.commit()
print("✅ 更新成功")

# ---------- 删除 ----------
cursor.execute("DELETE FROM users WHERE name = %s", ('王五',))
conn.commit()
print("✅ 删除成功")

cursor.close()
conn.close()

💡 PostgreSQL 的占位符也是 %s,和 MySQL 一样,但 SQL 语法各有差异(比如 SERIAL vs AUTO_INCREMENT)。文章源自网吧系统维护-https://www.58pxe.com/12969.html

四、MongoDB — 文档型 NoSQL 数据库

MongoDB 用 JSON 文档 存储数据,没有固定的表结构,适合灵活多变的数据模型文章源自网吧系统维护-https://www.58pxe.com/12969.html

连接 & 创建集合

from pymongo import MongoClient

# 连接 MongoDB(默认端口 27017)
client = MongoClient('mongodb://localhost:27017/')
db = client['testdb']            # 选择/创建数据库
collection = db['users']         # 选择/创建集合
print("✅ MongoDB 连接成功")

增删改查

# ---------- 新增(单条)----------
user1 = {
    'name': '张三',
    'age': 25,
    'city': '北京',
    'hobbies': ['篮球', '编程']
}
result = collection.insert_one(user1)
print(f"✅ 新增成功,ID: {result.inserted_id}")

# ---------- 新增(多条)----------
users = [
    {'name': '李四', 'age': 30, 'city': '上海', 'hobbies': ['旅游']},
    {'name': '王五', 'age': 28, 'city': '广州', 'hobbies': ['摄影', '跑步']},
]
collection.insert_many(users)
print("✅ 批量新增成功")

# ---------- 查询 ----------
for user in collection.find():
    print(f"  姓名: {user['name']}, 年龄: {user['age']}, 城市: {user['city']}, 爱好: {user.get('hobbies', [])}")

# 条件查询
for user in collection.find({'city': '北京'}):
    print(f"  北京用户: {user['name']}")

# ---------- 更新 ----------
collection.update_one(
    {'name': '张三'},
    {'$set': {'age': 26}}  # $set 只修改指定字段
)
print("✅ 更新成功")

# ---------- 删除 ----------
collection.delete_one({'name': '王五'})
print("✅ 删除成功")

client.close()

💡 MongoDB 的优势是数据不需要提前定义结构——同一个集合里的文档字段可以不同。
比如张三有 hobbies,李四没有,完全没问题。文章源自网吧系统维护-https://www.58pxe.com/12969.html

五、Redis — 闪电般快的键值数据库

Redis 把数据存在内存中,读写速度极快(微秒级),常用于缓存、计数器、消息队列文章源自网吧系统维护-https://www.58pxe.com/12969.html

连接 & 基础操作

import redis

# 连接 Redis
r = redis.Redis(
    host='localhost',
    port=6379,
    password='',       # 没有密码就留空
    decode_responses=True  # 自动解码为字符串
)
print("✅ Redis 连接成功")

字符串操作(最常用)

# ---------- 设置 / 获取 ----------
r.set('user:1001', '张三')
r.set('user:1002', '李四')

print(r.get('user:1001'))       # → 张三
print(r.exists('user:1001'))    # → True
print(r.keys('user:*'))         # → ['user:1001', 'user:1002']

# ---------- 带过期时间 ----------
r.setex('session:abc123', 60, '登录态')  # 60秒后自动过期
print(r.ttl('session:abc123'))  # → 剩余秒数

# ---------- 自增(计数器神器)----------
r.incr('page_views')            # → 1
r.incr('page_views')            # → 2
r.incrby('page_views', 10)      # → 12
print(f"页面访问量: {r.get('page_views')}")

# ---------- 删除 ----------
r.delete('user:1002')

哈希操作(存对象)

# ---------- 存储用户信息 ----------
r.hset('user:1001', mapping={
    'name': '张三',
    'age': 25,
    'city': '北京'
})

# 读取
print(r.hgetall('user:1001'))   # → {'name': '张三', 'age': '25', 'city': '北京'}
print(r.hget('user:1001', 'name'))  # → 张三

# 删除字段
r.hdel('user:1001', 'age')

💡 Redis 不适合存复杂查询场景,它的强项是。一般用作 MySQL/PostgreSQL 前面的缓存层。文章源自网吧系统维护-https://www.58pxe.com/12969.html

六、一图读懂:5 种数据库怎么选?

Python 操作数据库文章源自网吧系统维护-https://www.58pxe.com/12969.html

七、选型建议(初学者版)

新手学数据库 → 先玩 SQLite(零成本上手)
Web 开发     → MySQL 或 PostgreSQL(二选一)
数据灵活多变 → MongoDB(不用设计表结构)
追求速度     → Redis + 关系库搭配(做缓存层)

八、避坑指南

⚠️ 下面这 3 个错误,80% 的初学者都犯过文章源自网吧系统维护-https://www.58pxe.com/12969.html

❌ 错误 1:SQL 注入

# 千万不要这么写!
name = "张三'; DROP TABLE users; --"
# ✅ 正确写法:用占位符
cursor.execute("SELECT * FROM users WHERE name = ?", (name,))

❌ 错误 2:忘记 commit

# 插入数据后不 commit?数据丢了别怪我
cursor.execute("INSERT INTO users ...")
# ❌ 少了 conn.commit()

❌ 错误 3:不关连接

# 用完不关闭,连接越积越多,最后数据库拒绝连接
cursor.close()
conn.close()  # ✅ 记得关

💡 推荐用 with 上下文管理器,Python 会自动关闭连接:文章源自网吧系统维护-https://www.58pxe.com/12969.html

with sqlite3.connect('demo.db') as conn:
    cursor = conn.cursor()
    cursor.execute(...)
    conn.commit()
# 自动关闭,不用操心

总结

数据库
一句话记法
SQLite
自带小弟,开箱即用
MySQL
普及率最高,文档最多
PostgreSQL
功能最全,但稍微重一点
MongoDB
像 JSON 一样存数据
Redis
内存闪电侠,缓存之王

学完这篇,你基本能应付 90% 的 Python 数据库操作场景了。收藏起来,写代码的时候当字典查!文章源自网吧系统维护-https://www.58pxe.com/12969.html 文章源自网吧系统维护-https://www.58pxe.com/12969.html

版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
广告也精彩
admin
  • 本文由 发表于 2026年8月19日 23:08:10
  • 转载请务必保留本文链接:https://www.58pxe.com/12969.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: