博客
关于我
python操作SQLAlchemy
阅读量:423 次
发布时间:2019-03-06

本文共 2127 字,大约阅读时间需要 7 分钟。

SQLAlchemy 是一个功能强大的 ORM框架,基于数据库 API,通过对象关系映射将对象转换为 SQL 语句并执行操作。以下是关于 SQLAlchemy 的详细指南。

安装

通过 pip3 安装 SQLAlchemy:

pip3 install sqlalchemy

数据库连接

SQLAlchemy 使用 Dialect 与数据库通信,支持多种数据库,如 MySQL、PostgreSQL、Oracle 等。连接方式如下:

engine = create_engine(    "mysql+mysqldb://root:123@127.0.0.1:3306/s11",    max_overflow=5)

事务操作

在 SQLAlchemy 中,事务操作通过 engine.begin() 启动,确保数据一致性:

with engine.begin() as conn:    conn.execute("insert into table (x, y, z) values (1, 2, 3)")    conn.execute("my_special_procedure(5)")

数据库 schema

通过 MetaData 和 Table 定义数据库表结构:

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaDatametadata = MetaData()user = Table('user', metadata,    Column('id', Integer, primary_key=True),    Column('name', String(20)))

创建表结构:

engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)metadata.create_all(engine)

CRUD 操作

SQLAlchemy 提供了简单的增删改查方法:

  • 插入数据:
conn = engine.connect()conn.execute(user.insert(), {'id': 7, 'name': 'seven'})conn.close()
  • 删除数据:
sql = user.delete().where(user.c.id > 1)conn.execute(sql)
  • 更新数据:
sql = user.update().values(fullname=user.c.name)conn.execute(sql)
  • 查询数据:
result = conn.execute(sql).fetchall()

ORM 操作

使用 ORM 模块通过类操作数据库:

from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, Stringfrom sqlalchemy.orm import sessionmakerfrom sqlalchemy import create_engineengine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)Base = declarative_base()class User(Base):    __tablename__ = 'users'    id = Column(Integer, primary_key=True)    name = Column(String(50))Session = sessionmaker(bind=engine)session = Session()# 增u = User(id=2, name='sb')session.add(u)session.commit()# 删session.query(User).filter(User.id > 2).delete()session.commit()# 改session.query(User).filter(User.id > 2).update({'cluster_id': 0})session.commit()# 查ret = session.query(User).filter_by(name='sb').first()

注意事项

  • SQLAlchemy 本身不支持直接修改表结构,建议使用开源工具 [Alembic](https://sqlalchemy Alembic.readthedocs.io/en/latest/index.html) 进行数据库迁移。
  • 确保数据库连接安全,定期检查数据库线程状态:show status like 'Threads%'。

希望这篇文章能为您提供关于 SQLAlchemy 的全面的指导。

转载地址:http://pynuz.baihongyu.com/

你可能感兴趣的文章
python3读取redis返回数据带有'b'的问题
查看>>
Python3连接MySQL
查看>>
Python关于isinstance函数的解析 | 附Demo(全)
查看>>
Python3:setup.py:完成所有任务的PIP安装(Build_ext+Install)
查看>>
python4.0 gil_Python 并发编程系列--1、浅谈GIL历史及对多线程的影响
查看>>
python60行绘图程序_天底下最简单的QT画图板,就一个类,60行代码
查看>>
Python: AES加密与解密
查看>>
Python: Range() 最大尺寸;动态的还是静态的?
查看>>
Python: Windows下用 multiprocessing 的深坑
查看>>
python:Could not find platform independent libraries <prefix>解决方法
查看>>
Python:datetime tzinfo 时区名称文档
查看>>
Python:deepcopy(list) vs new_list = old_list[:]
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
查看>>
Python:TypeError:无法连接“str“和“int“对象
查看>>
Python:XPath 在 ElementTree 中不可用
查看>>
Python:从 FTP 服务器下载文件
查看>>
python:从列表中创建元组列表
查看>>
Python:从嵌套列表中删除重复项
查看>>