ORM(object relational mopper):关系对象映射。
作用:将对象转换成SQL语句,然后使用数据API执行SQL并获取执行结果。
SQLALchemy:是python提供的一个ORM模块,用来将对象转化为sql语句来操作数据库,其处于DB-API之上;
下面对上图执行步骤进行层层模拟:
Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:
MySQL-Pythonmysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>pymysqlmysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]MySQL-Connectormysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>cx_Oracleoracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html
准备工作安装,
依然是使用pip安装
pip install SQLAlchemy
第一步:
Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。
#!/usr/bin/env python
# -- coding = 'utf-8' --
# Author Allen Lee
# Python Version 3.5.1
# OS Windows 7
from sqlalchemy import create_engine#创建连接
engine = create_engine('mysql+pymysql://root:123@127.0.0.1:3306/mytest',max_overflow=3)#插入单条数据
engine_execute("insert into my_test (host,name) values ('127.0.0.1','Meta')"
)
#插入多条数据
engine_execute("insert into my_test (host,name) values (%s,%s)",(('192.168.132.127','Allen'),('10.0.0.32','Natasha'),)
)
engine_execute("insert into my_test (host,name) VALUES (%(ip)s,%(username)s)",ip="10.127.2.66," , username='tl_ccs'
)
#将执行结果返回给一个对象,然后在通过它的fetchall方法获取结果
result = engine.execute("select * from my_test")
result.fetchall()
#查看数据库连接
ret = engine_execute("show status like 'Threads% '")#事务操作
with engine.begin() as conn:conn.execute("insert into table (a,b,c) values (123,321,312)")conn.execute("my_first_procedure(3)")
conn = engine.connect()
with conn.begin():conn.execute("some statsment",{
'a':2,'b':321})
第二步:
ngine使用Schema Type创建一个特定的结构对象,之后通过SQL Expression Language将该对象转换成SQL语句,然后通过 ConnectionPooling 连接数据库,再然后通过 Dialect 执行SQL,并获取结果。
# #!/usr/bin/env python
# # -- coding = 'utf-8' --
# # Author Allen Lee
# # Python Version 3.5.1
# # OS Windows 7
#!/usr/bin/env python
# -*- coding:utf-8 -*-from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKeymetadata = MetaData()user = Table('user', metadata,Column('id', Integer, primary_key=True),Column('name', String(20)),
)color = Table('color', metadata,Column('id', Integer, primary_key=True),Column('name', String(20)),
)
engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/mytest", max_overflow=5)conn = engine.connect()# 创建SQL语句,INSERT INTO "user" (id, name) VALUES (:id, :name) conn.execute(user.insert(),{
'id':7,'name':'seven'})#增 # sql = user.insert().values(id=123, name='wu') #删 # sql = user.delete().where(user.c.id > 1) #改 # sql = user.update().values(fullname=user.c.name) # sql = user.update().where(user.c.name == 'jack').values(name='ed') #查 sql = select([user.c.name, color.c.name]).where(user.c.id==color.c.id) # sql = select([user.c.name]).order_by(user.c.name) # sql = select([user]).group_by(user.c.name)#获取查询结果 result = conn.execute(sql) print(result.fetchall()) #关闭连接 conn.close()
第三步:
使用 ORM/Schema Type/ SQL Expression Language/Engine/ConnectionPooling/Dialect
所有组件对数据进行操作。根据类创建对象,对象转换成SQL,执行SQL。
# #!/usr/bin/env python
# # -- coding = 'utf-8' --
# # Author Allen Lee
# # Python Version 3.5.1
# # OS Windows 7
#!/usr/bin/env python
# -*- coding:utf-8 -*-from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engineengine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/my_test", max_overflow=5)Base = declarative_base()
class User(Base):__tablename__ = 'users'id = Column(Integer, primary_key=True)name = Column(String(50))# 寻找Base的所有子类,按照子类的结构在数据库中生成对应的数据表信息 # Base.metadata.create_all(engine)Session = sessionmaker(bind=engine) session = Session()########## 增 ########## u = User(id=2, name='allen') session.add(u) session.add_all([User(id=3, name='natasha'),User(id=4, name='meta') ]) 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='allen').first()ret = session.query(User).filter_by(name='meta').all() print(ret)ret = session.query(User).filter(User.name.in_(['natasha','allen'])).all() print(ret)ret = session.query(User.name.label('name_label')).all() print(ret,type(ret))ret = session.query(User).order_by(User.id).all() print(ret)ret = session.query(User).order_by(User.id)[1:3] print(ret) session.commit()