SQLAlchemy:让数据库操作变得优雅又简单.

大家好呀!今天我要和大家分享Python最强大的ORM(对象关系映射)库——SQLAlchemy。它就像是Python和数据库之间的翻译官,让我们可以用写Python对象的方式来操作数据库,不用写复杂的SQL语句。无论你是要开发Web应用还是数据分析项目,掌握SQLAlchemy都能让你的数据库操作变得特别轻松!

1. 初识SQLAlchemy

首先,我们需要安装SQLAlchemy:

# 安装SQLAlchemy
pip install sqlalchemy

# 如果使用MySQL,还需要安装
pip install mysqlclient

# 导入必要的模块
from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

小贴士:SQLAlchemy支持多种数据库,包括SQLite、MySQL、PostgreSQL等。今天我们主要以SQLite为例,因为它不需要额外安装数据库服务器。

2. 连接数据库

# 创建数据库引擎(这里使用SQLite)
engine = create_engine('sqlite:///my_store.db', echo=True)

# 如果是MySQL,连接方式是这样的:
# engine = create_engine('mysql://username:password@localhost/dbname')

# 创建基类
Base = declarative_base()

小贴士:echo=True会打印出实际执行的SQL语句,对于学习和调试特别有帮助。等熟悉了之后,可以关闭它。

3. 定义模型类

模型类就像是数据库表的设计图纸,让我们用一个在线商店的例子来说明:

class Product(Base):
    __tablename__ = 'products'  # 指定表名
    
    id = Column(Integer, primary_key=True)  # 主键
    name = Column(String(100), nullable=False)  # 商品名称
    price = Column(Float, nullable=False)  # 价格
    stock = Column(Integer, default=0)  # 库存
    created_at = Column(DateTime)  # 创建时间
    
    def __repr__(self):
        return f"<Product(name='{self.name}', price={self.price})>"

# 创建所有表
Base.metadata.create_all(engine)

注意事项:

  • nullable=False表示这个字段不能为空

  • default设置字段的默认值

  • __repr__方法用于打印对象时的显示格式

4. 数据库会话(Session)

Session是我们与数据库交互的桥梁:

# 创建会话类
Session = sessionmaker(bind=engine)

# 创建会话实例
session = Session()

# 添加数据
new_product = Product(
    name="Python编程书",
    price=59.9,
    stock=100
)
session.add(new_product)
session.commit()  # 别忘了提交!

# 批量添加数据
products = [
    Product(name="Python速查手册", price=29.9, stock=50),
    Product(name="Python实战教程", price=89.9, stock=30)
]
session.add_all(products)
session.commit()

小贴士:记得及时commit(),否则数据不会真正写入数据库。如果操作出错,可以用session.rollback()回滚。

5. 查询数据

SQLAlchemy的查询功能特别强大:

# 查询所有产品
all_products = session.query(Product).all()

# 条件查询
cheap_books = session.query(Product).filter(Product.price < 50.0).all()

# 排序
expensive_first = session.query(Product).order_by(Product.price.desc()).all()

# 限制返回数量
top_5 = session.query(Product).limit(5).all()

# 复杂查询
results = session.query(Product).filter(
    Product.price.between(30, 100)  # 价格区间
).filter(
    Product.stock > 0  # 有库存
).order_by(
    Product.price  # 按价格排序
).all()

# 统计查询
from sqlalchemy import func
total_products = session.query(func.count(Product.id)).scalar()
avg_price = session.query(func.avg(Product.price)).scalar()

6. 更新和删除数据

# 更新单条数据
product = session.query(Product).filter_by(name="Python编程书").first()
if product:
    product.price = 69.9
    session.commit()

# 批量更新
session.query(Product).filter(
    Product.price < 30
).update(
    {Product.price: Product.price * 1.1}  # 涨价10%
)
session.commit()

# 删除数据
product_to_delete = session.query(Product).filter_by(name="Python速查手册").first()
if product_to_delete:
    session.delete(product_to_delete)
    session.commit()

7. 实用的查询技巧

# 使用like进行模糊查询
python_books = session.query(Product).filter(
    Product.name.like('%Python%')
).all()

# 使用in_进行范围查询
selected_ids = [1, 3, 5]
products = session.query(Product).filter(
    Product.id.in_(selected_ids)
).all()

# 使用and_、or_组合条件
from sqlalchemy import and_, or_
results = session.query(Product).filter(
    and_(
        Product.price < 100,
        or_(
            Product.stock > 50,
            Product.name.like('%Python%')
        )
    )
).all()

实战小练习:

  1. 创建一个简单的库存管理系统,包含商品的增删改查功能

  2. 实现一个带分页的商品列表查询

  3. 添加商品分类功能,实现一对多的关联查询

注意事项:

  • 记得妥善管理session,用完及时关闭

  • 大批量操作时注意使用批量接口

  • 合理使用索引提高查询性能

  • 注意SQL注入风险,使用参数化查询

小贴士:

  1. 使用with语句管理session更安全

  2. 可以用session.begin()开启事务

  3. 查询时可以用session.query(Product).get(id)直接获取指定id的记录

小伙伴们,今天的Python学习之旅就到这里啦!记得动手敲代码,有问题随时在评论区问我哦。祝大家学习愉快,Python学习节节高!

更多请关注公众号SurzZ.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值