百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

30天学会Python编程:18. Python数据库编程入门

off999 2025-07-08 22:07 3 浏览 0 评论

18.1 数据库基础

18.1.1 数据库类型对比

18.1.2 DB-API规范

核心接口

  1. connect() - 建立连接
  2. cursor() - 创建游标
  3. execute() - 执行SQL
  4. fetchone()/fetchall() - 获取结果
  5. commit()/rollback() - 事务控制

18.2 SQLite操作

18.2.1 基本CRUD

import sqlite3

# 创建连接
conn = sqlite3.connect('example.db', check_same_thread=False)
cursor = conn.cursor()

# 建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users
               (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

# 插入数据
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 25))

# 查询数据
cursor.execute("SELECT * FROM users WHERE age > ?", (20,))
print(cursor.fetchall())

# 提交事务
conn.commit()
conn.close()

18.2.2 高级特性

# 使用上下文管理器
with sqlite3.connect('example.db') as conn:
    conn.row_factory = sqlite3.Row  # 字典式访问
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users")
    for row in cursor:
        print(row['name'], row['age'])

# 内存数据库
mem_db = sqlite3.connect(':memory:')

18.3 MySQL/PostgreSQL

18.3.1 PyMySQL示例

import pymysql

# 连接MySQL
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    database='test',
    cursorclass=pymysql.cursors.DictCursor
)

try:
    with conn.cursor() as cursor:
        # 执行查询
        sql = "SELECT * FROM users WHERE email=%s"
        cursor.execute(sql, ('test@example.com',))
        result = cursor.fetchone()
        print(result)
finally:
    conn.close()

18.3.2 psycopg2示例

import psycopg2

# 连接PostgreSQL
conn = psycopg2.connect(
    host="localhost",
    database="test",
    user="postgres",
    password="password"
)

# 使用with自动提交/回滚
with conn:
    with conn.cursor() as cursor:
        cursor.execute("""
            INSERT INTO products (name, price)
            VALUES (%s, %s)
            RETURNING id
        """, ("Laptop", 999.99))
        product_id = cursor.fetchone()[0]
        print(f"插入记录ID: {product_id}")

18.4 ORM框架

18.4.1 SQLAlchemy核心

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 定义模型
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    age = Column(Integer)

# 创建引擎和会话
engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()

# 查询操作
users = session.query(User).filter(User.age > 20).all()
for user in users:
    print(user.name, user.age)

# 插入数据
new_user = User(name='Bob', age=30)
session.add(new_user)
session.commit()

18.4.2 Django ORM

# models.py
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

# 查询示例
from app.models import Product

# 创建记录
Product.objects.create(name="Mouse", price=29.99)

# 复杂查询
from django.db.models import Q, F
products = Product.objects.filter(
    Q(price__lt=100) | Q(name__startswith="M"),
    created_at__year=2023
).annotate(
    discounted_price=F('price')*0.9
)

18.5 NoSQL数据库

18.5.1 MongoDB

from pymongo import MongoClient

# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['users']

# 插入文档
user = {"name": "Alice", "age": 25, "hobbies": ["coding", "reading"]}
inserted_id = collection.insert_one(user).inserted_id

# 聚合查询
pipeline = [
    {"$match": {"age": {"$gt": 20}}},
    {"$group": {"_id": "$name", "count": {"$sum": 1}}}
]
results = collection.aggregate(pipeline)

18.5.2 Redis

import redis

# 连接Redis
r = redis.Redis(host='localhost', port=6379, db=0)

# 字符串操作
r.set('foo', 'bar')
print(r.get('foo'))  # b'bar'

# 哈希操作
r.hset('user:1000', mapping={
    'name': 'Alice',
    'age': '25'
})
print(r.hgetall('user:1000'))  # {b'name': b'Alice', b'age': b'25'}

18.6 数据库连接池

18.6.1 连接池实现

from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool

# 创建连接池
engine = create_engine(
    'mysql+pymysql://user:password@localhost/db',
    poolclass=QueuePool,
    pool_size=5,
    max_overflow=10,
    pool_timeout=30
)

# 使用连接
with engine.connect() as conn:
    result = conn.execute("SELECT * FROM users")
    print(result.fetchall())

18.6.2 连接池管理

import psycopg2
from psycopg2 import pool

# 创建连接池
connection_pool = psycopg2.pool.SimpleConnectionPool(
    minconn=1,
    maxconn=10,
    host="localhost",
    database="test",
    user="postgres",
    password="password"
)

# 获取连接
conn = connection_pool.getconn()
try:
    with conn.cursor() as cursor:
        cursor.execute("SELECT * FROM products")
        print(cursor.fetchall())
finally:
    connection_pool.putconn(conn)

18.7 应用举例

案例1:电商订单

from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float, DateTime

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    orders = relationship("Order", back_populates="user")

class Product(Base):
    __tablename__ = 'products'
    id = Column(Integer, primary_key=True)
    name = Column(String(100))
    price = Column(Float)
    order_items = relationship("OrderItem", back_populates="product")

class Order(Base):
    __tablename__ = 'orders'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    created_at = Column(DateTime)
    user = relationship("User", back_populates="orders")
    items = relationship("OrderItem", back_populates="order")

class OrderItem(Base):
    __tablename__ = 'order_items'
    id = Column(Integer, primary_key=True)
    order_id = Column(Integer, ForeignKey('orders.id'))
    product_id = Column(Integer, ForeignKey('products.id'))
    quantity = Column(Integer)
    order = relationship("Order", back_populates="items")
    product = relationship("Product", back_populates="order_items")

# 使用示例
engine = create_engine('sqlite:///ecommerce.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

# 创建测试数据
new_user = User(name="Alice")
session.add(new_user)

product1 = Product(name="Laptop", price=999.99)
product2 = Product(name="Mouse", price=29.99)
session.add_all([product1, product2])

order = Order(user=new_user)
order.items = [
    OrderItem(product=product1, quantity=1),
    OrderItem(product=product2, quantity=2)
]
session.add(order)
session.commit()

# 查询用户订单
user = session.query(User).filter_by(name="Alice").first()
for order in user.orders:
    print(f"订单 {order.id}:")
    for item in order.items:
        print(f"  - {item.product.name} x{item.quantity}")

案例2:缓存策略实现

import sqlite3
import redis
import json
from datetime import datetime

class CachedDatabase:
    """带Redis缓存的数据库访问层"""
    
    def __init__(self, db_file=':memory:'):
        self.redis = redis.Redis(host='localhost', port=6379, db=0)
        self.db_conn = sqlite3.connect(db_file)
        self._init_db()
    
    def _init_db(self):
        cursor = self.db_conn.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS articles
                       (id INTEGER PRIMARY KEY, title TEXT, content TEXT, 
                       created_at TIMESTAMP)''')
        self.db_conn.commit()
    
    def get_article(self, article_id):
        """获取文章(优先从缓存读取)"""
        cache_key = f"article:{article_id}"
        cached_data = self.redis.get(cache_key)
        
        if cached_data:
            print("从缓存读取")
            return json.loads(cached_data)
        
        print("从数据库读取")
        cursor = self.db_conn.cursor()
        cursor.execute("SELECT * FROM articles WHERE id=?", (article_id,))
        row = cursor.fetchone()
        
        if row:
            article = {
                'id': row[0],
                'title': row[1],
                'content': row[2],
                'created_at': row[3]
            }
            # 写入缓存(60秒过期)
            self.redis.setex(cache_key, 60, json.dumps(article))
            return article
        return None
    
    def create_article(self, title, content):
        """创建新文章(自动清除相关缓存)"""
        cursor = self.db_conn.cursor()
        created_at = datetime.now().isoformat()
        cursor.execute("INSERT INTO articles (title, content, created_at) VALUES (?, ?, ?)",
                      (title, content, created_at))
        self.db_conn.commit()
        
        # 获取新插入的ID
        article_id = cursor.lastrowid
        
        # 清除可能存在的缓存
        self.redis.delete(f"article:{article_id}")
        
        return article_id

# 使用示例
cache_db = CachedDatabase()

# 创建测试文章
article_id = cache_db.create_article(
    "Python数据库编程",
    "本文介绍Python中的各种数据库操作方法..."
)

# 第一次读取(从数据库)
article = cache_db.get_article(article_id)

# 第二次读取(从缓存)
article = cache_db.get_article(article_id)

18.8 知识图谱


持续更新Python编程学习日志与技巧,敬请关注!


#编程# #学习# #在头条记录我的2025# #python#


相关推荐

安装python语言,运行你的第一行代码

#01安装Python访问Python官方(https://www.python.org/),下载并安装最新版本的Python。确保安装过程中勾选“Addpython.exetoPAT...

Python推导式家族深度解析:字典/集合/生成器的艺术

一、为什么需要其他推导式?当你在处理数据时:o需要快速去重→集合推导式o要建立键值映射→字典推导式o处理海量数据→生成器表达式这些场景是列表推导式无法完美解决的,就像工具箱需要不同工...

别再用循环创建字典了!Python推导式让你的代码起飞

当同事还在用for循环吭哧吭哧创建字典时,我早已用推导式完成3个需求了!这个被90%新手忽视的语法,今天让你彻底掌握字典推导式的4大高阶玩法,文末彩蛋教你用1行代码搞定复杂数据转换!基础语法拆解#传...

什么是Python中的生成器推导式?(python生成器的好处)

编程派微信号:codingpy本文作者为NedBatchelder,是一名资深Python工程师,目前就职于在线教育网站Edx。文中蓝色下划线部分可“阅读原文”后点击。Python中有一种紧凑的语法...

Python 列表转换为字符串:实用指南

为什么在Python中将列表转换为字符串?Python列表非常灵活,但它们并非在所有地方都适用。有时你需要以人类可读的格式呈现数据——比如在UI中显示标签或将项目保存到CSV文件。可能还...

生成器表达式和列表推导式(生成器表达式的计算结果)

迭代器的输出有两个很常见的使用方式,1)对每一个元素执行操作,2)选择一个符合条件的元素子集。比如,给定一个字符串列表,你可能想去掉每个字符串尾部的空白字符,或是选出所有包含给定子串的字符串。列表...

python学习——038python中for循环VS列表推导式

在Python中,for循环和列表推导式(ListComprehension)都可以用于创建和处理列表,但它们的语法、性能和适用场景有所不同。以下是两者的详细对比:1.语法结构for循环使用...

python中列表推导式怎么用?(列表 python)

这个问题,我们不妨用近期很火的ChatGPT来试试,来看看人工智能是如何解答的?在Python中,列表解析是一种简洁的方法,用于生成列表。它是一种快速,简洁的方法,可以在一行代码中生成列表,而不需...

Python列表推导式:让你的代码优雅如诗!

每次写for循环都要三四行代码?处理数据时总被嵌套结构绕晕?学会列表推导式,一行代码就能让代码简洁十倍!今天带你解锁这个Python程序员装(偷)逼(懒)神器!一、为什么你需要列表推导式?代码...

python学习——038如何将for循环改写成列表推导式

在Python里,列表推导式是一种能够简洁生成列表的表达式,可用于替换普通的for循环。下面是列表推导式的基本语法和常见应用场景。基本语法result=[]foriteminite...

太牛了!Python 列表推导式,超级总结!这分析总结也太到位了!

Python列表推导式,超级总结!一、基本概念列表推导式是Python中创建列表的一种简洁语法,它允许你在一行代码内生成列表,替代传统的for循环方式。其核心思想是**"对可迭代对...

25-2-Python网络编程-TCP 编程示例

2-TCP编程示例应用程序通常通过“套接字”(socket)向网络发出请求或者应答网络请求,使主机间或者一台计算机上的进程间可以通信。Python语言提供了两种访问网络服务的功能。其中低级别的网络服...

python编程的基础与进阶(周兴富)(python编程基础视频)

前不久我发文:《懂了,if__name=='__main__'》。想不到的是,这个被朋友称之为“读晕了”的文章,其收藏量数百,有效阅读量竟然过万。所谓“有效阅读量”,就是读到尾部才退...

Python 闭包:深入理解函数式编程的核心概念

一、简介在Python编程领域,闭包(Closure)是一个既基础又强大的概念,它不仅是装饰器、回调函数等高级特性的实现基础,更是函数式编程思想的重要体现。理解闭包的工作原理,能够帮助开发者编写出...

Python小白逆袭!7天吃透PyQt6,独立开发超酷桌面应用

PythonGUI编程:PyQt6从入门到实战的全面指南在Python的庞大生态系统中,PyQt6作为一款强大的GUI(GraphicalUserInterface,图形用户界面)编程框架,为开...

取消回复欢迎 发表评论: