上一篇文章,介紹了原生的pyMySQL的方式來操作mysql。這篇文章將要學(xué)習(xí)下SQLAchemy使用mysql的規(guī)則
10年積累的成都網(wǎng)站制作、網(wǎng)站建設(shè)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先建設(shè)網(wǎng)站后付款的網(wǎng)站建設(shè)流程,更有蘭西免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
ORM框架有兩種形式:
第一種是DB first,就是需要手動(dòng)創(chuàng)建數(shù)據(jù)庫和表,然后ORM框架,自動(dòng)生成代碼類的方法;
第二種是code first,就是手動(dòng)創(chuàng)建數(shù)據(jù)庫,然后通過寫代碼類的方法,ORM框架來自動(dòng)生成表和數(shù)據(jù)的方法
SQLAlchemy是Python編程語言下的一款ORM框架,該框架建立在數(shù)據(jù)庫API之上,使用關(guān)系對(duì)象映射進(jìn)行數(shù)據(jù)庫操作,簡言之便是:將對(duì)象轉(zhuǎn)換成SQL,然后使用數(shù)據(jù)API執(zhí)行SQL并獲取執(zhí)行結(jié)果。
作用:
- 提供簡單的規(guī)則,2. 自動(dòng)轉(zhuǎn)換成SQL語句
pip3 install SQLAlchemy
or
easy_install SQLAlchemy
SQLAlchemy的結(jié)構(gòu)圖,如下:
SQLAlchemy本身是不會(huì)連接數(shù)據(jù)庫的,他是通過"DBAPI"這個(gè)模塊api接口來實(shí)現(xiàn)對(duì)數(shù)據(jù)庫連接的,而它本身會(huì)更加Dialect里面的設(shè)置,來確定你是什么數(shù)據(jù)庫,如何轉(zhuǎn)化sql語句的功能。
使用 Engine/ConnectionPooling/Dialect 進(jìn)行數(shù)據(jù)庫操作,Engine使用ConnectionPooling連接數(shù)據(jù)庫,然后再通過Dialect執(zhí)行SQL語句。
常見的DBAPI在官方的sqlachemy里面有介紹和使用方法,下面列出幾個(gè)案例:
MySQL-Python
mysql+mysqldb://:@[:]/
pymysql
mysql+pymysql://:@/[?]
MySQL-Connector
mysql+mysqlconnector://:@[:]/
cx_Oracle
oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
更多詳見:http://docs.sqlalchemy.org/en/latest/dialects/index.html
#導(dǎo)入模塊
from sqlalchemy import create_engine
#創(chuàng)建連接,是通過create_engine來創(chuàng)建連接的
engine = create_engine("mysql+pymysql://kk:123@localhost:3306/pysqltest",max_overflow=5)
#執(zhí)行SQL
cur = engine.execute(
"insert into t1(name) VALUES ('rr')"
)
結(jié)果截圖
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
# 執(zhí)行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)"
# )
# 新插入行自增ID
# cur.lastrowid
# 執(zhí)行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),]
# )
# 執(zhí)行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)",
# host='1.1.1.99', color_id=3
# )
# 執(zhí)行SQL
# cur = engine.execute('select * from hosts')
# 獲取第一行數(shù)據(jù)
# cur.fetchone()
# 獲取第n行數(shù)據(jù)
# cur.fetchmany(3)
# 獲取所有數(shù)據(jù)
# cur.fetchall()
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index,CHAR,VARCHAR
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine
engine=create_engine("mysql+pymysql://kk:123@localhost:3306/pysqltest?charset=utf8",max_overflow=5)
Base=declarative_base()
#創(chuàng)建單表
class Users(Base):
__tablename__ = 'users'
id = Column(Integer,primary_key=True)
name = Column(String(32))
gender = Column(CHAR(32))
__table_args__ = (
UniqueConstraint('id','name',name='uix_id_name'),
Index('ix_id_name','name','gender')
# Index 要把名字寫在最前面
)
def init_db():
Base.metadata.create_all(engine)
def drop_db():
Base.metadata.drop_all(engine)
init_db()
執(zhí)行結(jié)果:
要想對(duì)表中的數(shù)據(jù)進(jìn)行操作,需要能拿到一個(gè)類似pymysql的游標(biāo)的功能,在這里它是一個(gè)session。
Session = sessionmaker(bind=engine)
session = Session()
類 -> 表
對(duì)象 -> 行
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index,CHAR,VARCHAR
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine
engine=create_engine("mysql+pymysql://kk:123@localhost:3306/pysqltest?charset=utf8",max_overflow=5)
session=sessionmaker(bind=engine)
session=session()
Base=declarative_base()
#創(chuàng)建單表
class Users(Base):
__tablename__ = 'users'
id = Column(Integer,primary_key=True)
name = Column(String(32))
gender = Column(CHAR(32))
__table_args__ = (
UniqueConstraint('id','name',name='uix_id_name'),
Index('ix_id_name','name','gender')
# Index 要把名字寫在最前面
)
def init_db():
Base.metadata.create_all(engine)
def drop_db():
Base.metadata.drop_all(engine)
###增加功能
obj1 =Users(name='xx',gender='女')
session.add(obj1)
#添加過個(gè)values的方法
#obj2=[
# Users(name='yy',gender='男'),
# Users(name='zz',gender='女'),
# Users(name='rr',gender='男'),
#]
#session.add_all(obj2)
session.commit()
session.close()
####查找
user_list=session.query(Users).all()
for row in user_list:
print(row.id,row.name,row.gender)
# user_type_list = session.query(UserType.id,UserType.title).filter(UserType.id > 2)
# for row in user_type_list:
# print(row.id,row.title)
session.query(Users).filter(Users.id ==4).delete()
session.query(Users).filter(Users.id ==1).update({'gender':'中性'})
#給添加變長字符串長度的用下面這種
session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"}, synchronize_session=False)
#把所有數(shù)字自動(dòng)加1用下面這種
session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
session.commit()
+參考文章
# 條件
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.
# select * from b where id in (select id from tb2)
# 2 select * from (select * from tb) as B
# q1 = session.query(UserType).filter(UserType.id > 0).subquery()
# result = session.query(q1).all()
# print(result)
# 3
# select
# id ,
# (select * from users where users.user_type_id=usertype.id)
# from usertype;
# session.query(UserType,session.query(Users).filter(Users.id == 1).subquery())
# session.query(UserType,Users)
# result = session.query(UserType.id,session.query(Users).as_scalar())
# print(result)
# result = session.query(UserType.id,session.query(Users).filter(Users.user_type_id==UserType.id).as_scalar())
# print(result)