Python操作mysql之SQLAchemy(ORM框架)

时间:2023-01-20 17:55:56

SQLAchemy

SQLAchemy

  解析:

SQLAchemy是python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,

简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。

ORM框架的作用就是把数据库表的一行记录与一个对象互相做自动转换。 正确使用ORM的前提是了解关系数据库的原理。 ORM就是把数据库表的行与相应的对象建立关联,互相转换。 由于关系数据库的多个表还可以用外键实现一对多、多对多等关联,相应地, ORM框架也可以提供两个对象之间的一对多、多对多等功能。

  安装:

pip3 install SQLALchemy

  

SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,

根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:

MySQL-Python
mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> pymysql
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]

更多:

MySQL-Python
mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> pymysql
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] MySQL-Connector
mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname> cx_Oracle
oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...] 更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html

一、内部处理

使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,

然后再通过Dialect执行SQL语句。

#!/usr/bin/env python
# -*- coding:utf- -*-
from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=) # 执行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)"
# ) # 新插入行自增ID
# cur.lastrowid # 执行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', ),('1.1.1.221', ),]
# ) # 执行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)",
# host='1.1.1.99', color_id=
# ) # 执行SQL
# cur = engine.execute('select * from hosts')
# 获取第一行数据
# cur.fetchone()
# 获取第n行数据
# cur.fetchmany()
# 获取所有数据
# cur.fetchall()

二、ORM功能使用

使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。

根据类创建对象,对象转换成SQL,执行SQL。

  1、创建表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) Base = declarative_base() # 创建单表
class Users(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
extra = Column(String(16)) __table_args__ = (
UniqueConstraint('id', 'name', name='uix_id_name'),
Index('ix_id_name', 'name', 'extra'),
) # 一对多
class Favor(Base):
__tablename__ = 'favor'
nid = Column(Integer, primary_key=True)
caption = Column(String(50), default='red', unique=True) class Person(Base):
__tablename__ = 'person'
nid = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=True)
favor_id = Column(Integer, ForeignKey("favor.nid")) # 多对多
class Group(Base):
__tablename__ = 'group'
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True, nullable=False)
port = Column(Integer, default=22) class Server(Base):
__tablename__ = 'server' id = Column(Integer, primary_key=True, autoincrement=True)
hostname = Column(String(64), unique=True, nullable=False) class ServerToGroup(Base):
__tablename__ = 'servertogroup'
nid = Column(Integer, primary_key=True, autoincrement=True)
server_id = Column(Integer, ForeignKey('server.id'))
group_id = Column(Integer, ForeignKey('group.id')) def init_db(): # 创建表
Base.metadata.create_all(engine) def drop_db(): # 删除表
Base.metadata.drop_all(engine) # drop_db()
# init_db()

  2、操作表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine # 指定字符集、最大连接池数
engine = create_engine("mysql+pymysql://root:suoning@127.0.0.1:3306/suoning4?charset=utf8", max_overflow=5) Base = declarative_base() # 创建单表
class Users(Base):
# 表名
__tablename__ = 'users'
# 表字段
id = Column(Integer, primary_key=True) # 主键、默认自增
name = Column(String(32))
extra = Column(String(16)) __table_args__ = (
UniqueConstraint('id', 'name', name='uix_id_name'), # 唯一索引
Index('ix_id_name', 'name', 'extra'), # 普通索引
) def __repr__(self):
# 查是输出的内容格式,本质还是对象
return "%s-%s" %(self.id, self.name) # 一对多
class Favor(Base):
__tablename__ = 'favor'
nid = Column(Integer, primary_key=True)
caption = Column(String(50), default='red', unique=True) # 默认值、唯一索引 def __repr__(self):
return "%s-%s" %(self.nid, self.caption) class Person(Base):
__tablename__ = 'person'
nid = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=True)
favor_id = Column(Integer, ForeignKey("favor.nid"))
# 与生成表结构无关,仅用于查询方便
favor = relationship("Favor", backref='pers') # 多对多
class ServerToGroup(Base):
# 关系表要放对应表上面,否则找不到
__tablename__ = 'servertogroup'
nid = Column(Integer, primary_key=True, autoincrement=True)
server_id = Column(Integer, ForeignKey('server.id')) # 外键
group_id = Column(Integer, ForeignKey('group.id')) group = relationship("Group", backref='s2g')
server = relationship("Server", backref='s2g') class Group(Base):
__tablename__ = 'group'
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True, nullable=False) # 不能为空
port = Column(Integer, default=22)
# group = relationship('Group',secondary=ServerToGroup,backref='host_list') class Server(Base):
__tablename__ = 'server' id = Column(Integer, primary_key=True, autoincrement=True) # 自增
hostname = Column(String(64), unique=True, nullable=False) def init_db():
# 创建表
Base.metadata.create_all(engine) def drop_db():
# 删除表
Base.metadata.drop_all(engine) # 先实例化sessionmaker类,Session对象加括号执行类下的__call__方法,
# 得到session对象,所以session可以调用Session类下的add,add_all等方法
Session = sessionmaker(bind=engine) # 指定引擎
session = Session()

obj = Users(name='alex1', exeven='sd')
session.add(obj)
session.add_all([
Users(name='alex2', exeven='sd'),
Users(name='alex3', exeven='sd'),
])
session.commit()

session.query(users.id).filter(Users.id > 2).delete()
session.commit()  

session.query(Users).filter(Users.id > 2).update({"name" : "999"})
session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"},
synchronize_session=False)
session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
session.commit()

ret = session.query(Users).all()
ret = session.query(Users.name, Users.extra).all()
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter_by(name='alex').first()

其他

# 条件
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()
ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()
ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()
from sqlalchemy import and_, or_
ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
ret = session.query(Users).filter(
or_(
Users.id < 2,
and_(Users.name == 'eric', Users.id > 3),
Users.extra != ""
)).all() # 通配符
ret = session.query(Users).filter(Users.name.like('e%')).all()
ret = session.query(Users).filter(~Users.name.like('e%')).all() # 限制
ret = session.query(Users)[1:2] # 排序
ret = session.query(Users).order_by(Users.name.desc()).all()
ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all() # 分组
from sqlalchemy.sql import func ret = session.query(Users).group_by(Users.extra).all()
ret = session.query(
func.max(Users.id),
func.sum(Users.id),
func.min(Users.id)).group_by(Users.name).all() ret = session.query(
func.max(Users.id),
func.sum(Users.id),
func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all() # 连表 ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all() ret = session.query(Person).join(Favor).all() ret = session.query(Person).join(Favor, isouter=True).all() # 组合
q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union(q2).all() q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union_all(q2).all()

三、单表与多表

  1、一对多

# !/usr/bin/env python
# -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine engine = create_engine('mysql+pymysql://root:123456@127.0.0.1:3306/kong') # 连接已存在的数据库 Base = declarative_base() # 根据SQL创建一个基类 class Son(Base):
__tablename__ = 'son' id = Column(Integer, primary_key=True)
name = Column(String(32))
age = Column(String(16)) father_id = Column(Integer, ForeignKey('father.id')) # 外键(外键放在哪个类下,哪个就是多) class Father(Base):
__tablename__ = 'father' id = Column(Integer, primary_key=True)
name = Column(String(32))
age = Column(String(16)) son = relationship('Son') # 是取与son关联的数据(通过父关联子找)
# son = relationship('Son', backfe="father") # backfe="father"是(“backfe”是关键字通过子关联父找) Base.metadata.create_all(engine) # 创建所有的表
# Base.metadata.drop_all(engine) # 删除表 Session = sessionmaker(bind=engine)
session = Session()
f1 = Father(name='alvin', age=50)
# session.commit()
w1 = Son(name='little alvin1', age=4)
w2 = Son(name='little alvin2', age=5)
w3 = Son(name='little alvin3', age=5)
f1.son = [w1, w2, w3] session.add_all([f1, w1, w2])
session.commit()

关联查询(relationship)

#!/usr/bin/env python
#-*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine engine = create_engine('mysql+pymysql://root@127.0.0.1:3306/kong') Base = declarative_base() class Son(Base):
__tablename__ = 'son'
id = Column(Integer, primary_key=True)
name = Column(String(32))
age= Column(String(16)) father_id=Column(Integer,ForeignKey('father.id')) # 外键关系,关联两张表的关系(下面的关联查询) class Father(Base):
__tablename__ ='father' id = Column(Integer, primary_key=True)
name = Column(String(32))
age= Column(String(16)) son=relationship('Son',backref='father') # 相当于在father类下写father=relationship('father')和在son类下写son=relationship('son')一样的效果
# 通过儿子关联并找父亲的信息;通过父亲关联并找儿子的信息(这就是relationship的关系) Base.metadata.create_all(engine)
# Base.metadata.drop_all(engine)
Session = sessionmaker(bind=engine)
session = Session() # ret=session.query(Father.name.label('kkk'),Son.name.label('ppp')).join(Son) # (关联查询)关联儿子并拿出所有的符合条件的数据
# print(ret) # Son.name.label('ppp')) 是给son.name起一个名字;label是关键字 #f1=session.query(Father).filter_by(id=1).first() # 查询父亲的信息
# print(f1.son)
# s1=session.query(Son).filter_by(id=2).first() # # 查询儿子的信息;filter_by是键值对形式的查询;filter是条件的形式查询
# print(s1.father.name,s1.name) f1=session.query(Father).filter_by(id=1).first() # 不加first这类的索引只能得到sql语句不能得到具体的数据。
w4=Son(name='little alvin4',age=5) # 创建一条数据(这就是relationship内部帮实现的)
f1.son.append(w4) # 插入这一条信息 session.add(f1)
session.commit()

  2、多对多  

# !/usr/bin/env python
# -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine engine = create_engine('mysql+pymysql://root:123456@127.0.0.1:3306/kong?charset=utf8') # 连接已存在的数据库; 插入汉子就要添加编码解析?charset=utf8 Base = declarative_base() # 根据SQL创建ORM的基类 class Men_to_Wemon(Base):
__tablename__ = 'men_to_wemon'
nid = Column(Integer, primary_key=True)
id = Column(Integer, primary_key=True)
men_id = Column(Integer, ForeignKey('men.id'))
women_id = Column(Integer, ForeignKey('women.id')) class Men(Base):
__tablename__ = 'men'
id = Column(Integer, primary_key=True)
name = Column(String(32))
age = Column(String(16))
# gf = relationship("Women", secondary=Men_to_Wemon.__table__) # 可以在下面的backref='gf'替代,表示关联;
# secondary如果有第三张表会自动关联必须加__table__, class Women(Base):
__tablename__ = 'women'
id = Column(Integer, primary_key=True)
name = Column(String(32))
age = Column(String(16))
bf = relationship("Men", secondary=Men_to_Wemon.__table__, backref='gf') Base.metadata.create_all(engine) # 在数据库生成表
Session = sessionmaker(bind=engine) # 通过激活sessionmaker的__call__方法来return一个Session实例(Session类下提供了增删改查的具体方法)
session = Session() # 下面是插入数据
# m1 = Men(name='alex', age=18)
# m2 = Men(name='wusir', age=18)
# w1 = Women(name='如花', age=26)
# w2 = Women(name='铁蛋', age=30)
# session.add_all([m1, m2, w1, w2])
# session.commit() # 提交添加的数据 # t1 = Men_to_Wemon(men_id=1, women_id=2) # 第三张表,让之前的两张表创建一个对应关系 m1 = session.query(Men).filter_by(id=2).first() # 查询Men的信息是(列表)
w1 = session.query(Women).all() # 查询Women的信息是(列表)
m1.gf = w1 # 让查询的信息创建关系 session.add_all([m1])
session.commit() # 需要注意的地方:
# 1 查询时如果不加all,first等,得到的是sql语句,加上后,才是具体的结果;而all的结果是一个列表。
# 2 m1.gf是一个列表,里面存放着符合条件的对象。
# 3 filter与filter_by的区别:filter是拿键值对的参数,filter_by是拿条件判断的参数。

更多详情:http://www.cnblogs.com/yuanchenqi/articles/5638282.html

     http://www.cnblogs.com/wupeiqi/articles/5713330.html

实例:http://www.cnblogs.com/yuanchenqi/articles/5736332.html