SQLAlcvchem
一.安装(稳定版的1.2.17)
二.一般使用(切记切记不要使用模块的名字作为项目名字,否则会出现玄学解决不了的问题------坑)
#.导入SQLALchemy
from sqlalchemy.ext.declarative import declarative_base #.创建ORM模型基类
Base = declarative_base() #.导入ORM对应数据类型的字段
from sqlalchemy import Column,Integer,String #.创建ORM对象
class User(Base):
__tablename__ ="user" #创建表名字
id = Column(Integer,primary_key=True,autoincrement=True) #创建id主键自增长
name = Column(String(),index=True) #5创建数据库链接
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/day127?charset=utf8") #6去数据库中创建与User所对应的数据库
Base.metadata.create_all(engine)
三.创建外键关联
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base()
from sqlalchemy import Column,String,ForeignKey,Integer
from sqlalchemy.orm import relationship class Student(Base):
__tablename__ ="student"
id = Column(Integer,primary_key=True)
name = Column(String())
school_id = Column(Integer,ForeignKey("school.id")) stu2sch = relationship("School",backref="sch2stu") class School(Base):
__tablename__="school"
id = Column(Integer,primary_key=True)
name = Column(String()) from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/127?charset=utf8") Base.metadata.create_all(engine)
四.增加数据
# 通过SQLAlchemy对数据表进行增删改查
# crud == 增删改查
# 想要操纵数据库 打开数据库连接
# from sqlalchemy import create_engine
# engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/day127?charset=utf8")
from create_table import engine
# 创建会话 - 打开数据库连接
from sqlalchemy.orm import sessionmaker
# 创建会话窗口
Session = sessionmaker(engine)
# 打开会话窗口
db_session = Session() # .增加数据 == insert
# # insert into user(name) values("DragonFire")
# from create_table import User
# user_obj = User(name="Ywb")
# # 通过db_session已经打开会话窗口 提交数据
# db_session.add(user_obj) # insert into
# # 执行会话窗口中的所有操作
# db_session.commit() #rud
# db_session.close() # .增加批量数据
# from create_table import User
# db_session.add_all([
# User(name="AlexDSB"),
# User(name="DragonFire"),
# User(name="赵丽颖")
# ])
#
# db_session.commit()
# db_session.close() #扩展:
# from create_table import User
# user1 = User(name="")
# user2 = User(name="")
# user3 = User(name="")
#
# db_session.add(user1)
# db_session.add(user2)
# db_session.add(user3)
#
# db_session.commit()
# db_session.close()
4.1外键增加数据
# 添加数据
from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School Session = sessionmaker(engine)
db_session = Session() # .添加数据 - 笨
# sch_obj = School(name="OldBoyBeijing")
# db_session.add(sch_obj)
# db_session.commit()
#
# sch = db_session.query(School).filter(School.name == "OldBoyBeijing").first()
# stu_obj = Student(name="DragonFire",school_id=sch.id)
# db_session.add(stu_obj)
# db_session.commit()
# db_session.close() # .添加数据 - 正向 relationship 版
# stu_obj = Student(name="小笼包",stu2sch=School(name="OldBoyShenzhen"))
# db_session.add(stu_obj)
# db_session.commit()
# db_session.close() # .添加数据 - 反向 relationship 版
# sch_obj = School(name="OldBoyShanghai")
# sch_obj.sch2stu = [Student(name="赵丽颖"),Student(name="陈妍希")]
# db_session.add(sch_obj)
# db_session.commit()
# db_session.close()
五.删除数据
# 添加数据
from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School Session = sessionmaker(engine)
db_session = Session() # .添加数据 - 笨
# sch_obj = School(name="OldBoyBeijing")
# db_session.add(sch_obj)
# db_session.commit()
#
# sch = db_session.query(School).filter(School.name == "OldBoyBeijing").first()
# stu_obj = Student(name="DragonFire",school_id=sch.id)
# db_session.add(stu_obj)
# db_session.commit()
# db_session.close() # .添加数据 - 正向 relationship 版
# stu_obj = Student(name="小笼包",stu2sch=School(name="OldBoyShenzhen"))
# db_session.add(stu_obj)
# db_session.commit()
# db_session.close() # .添加数据 - 反向 relationship 版
# sch_obj = School(name="OldBoyShanghai")
# sch_obj.sch2stu = [Student(name="赵丽颖"),Student(name="陈妍希")]
# db_session.add(sch_obj)
# db_session.commit()
# db_session.close()
5.1外键删除数据
# 添加数据
from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School Session = sessionmaker(engine)
db_session = Session() # 删除数据
sch = db_session.query(School).filter(School.name=="OldBoyShanghai").first()
db_session.query(Student).filter(Student.school_id == sch.id).delete()
db_session.commit()
db_session.close()
六.查询数据
# 查询
# 会话窗口
from sqlalchemy.orm import sessionmaker
from create_table import engine Session = sessionmaker(engine)
db_session = Session() from create_table import User # .简单查询
# select * from table
# user_list = db_session.query(User).all()
# for row in user_list:
# print(row.id,row.name)
# user = db_session.query(User).first()
# print(user.id,user.name) # .带条件的查询
# user_list = db_session.query(User).filter(User.id == ).all()
# print(user_list[].id,user_list[].name) # user = db_session.query(User).filter_by(id=).first()
# print(user.id,user.name) # user_list = db_session.query(User).filter(User.id >= ).all()
# for row in user_list:
# print(row.name,row.id) # 扩展 查看sql语句
# sql = db_session.query(User).filter(User.id >= )
# print(sql)
6.1外键查询
# 添加数据
from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School Session = sessionmaker(engine)
db_session = Session() # .查询数据 - relationship 版 正向
# stu = db_session.query(Student).all()
# for row in stu:
# print(row.id,row.name,row.school_id,row.stu2sch.name) # .查询数据 - relationship 版 反向
# sch = db_session.query(School).all()
# for school in sch:
# for student in school.sch2stu:
# print(school.id,school.name,student.name)
6.2补充--查询
# 高级版查询操作,厉害了哦
# 老规矩
from create_table import User, engine
from sqlalchemy.orm import sessionmaker Session = sessionmaker(engine)
db_session = Session() # 查询数据表操作
# and or
# res = db_session.query(User).filter(User.id == or User.name == "DragonFire").all()
# print(res[].name,res)
#
# if False and True:
# print("lihaile") # from sqlalchemy.sql import and_ , or_
# ret = db_session.query(User).filter(and_(User.id == , User.name == 'DragonFire')).all()
# print(ret)
# ret = db_session.query(User).filter(or_(User.id == , User.name == 'DragonFire')).all()
# print(ret)
# ret = db_session.query(User).filter_by(id=,name="DragonFire").all()
# print(ret) # 查询所有数据
# r1 = db_session.query(User).all() # 查询数据 指定查询数据列 加入别名
# r2 = db_session.query(User.id.label("uid"),User.name.label("username")).first()
# print(r2.uid,r2.username) # NBDragon # 表达式筛选条件
# r3 = db_session.query(User).filter(User.name == "DragonFire").all() # 原生SQL筛选条件
# r4 = db_session.query(User).filter_by(name='DragonFire').all()
# r5 = db_session.query(User).filter_by(name='DragonFire').first() # 字符串匹配方式筛选条件 并使用 order_by进行排序
# from sqlalchemy.sql import text
# r6 = db_session.query(User).filter(text("id=:value and name=:name")).params(value=, name='DragonFire').first()
# print(r6.name) # 原生SQL查询
# r7 = db_session.query(User).from_statement(text("SELECT * FROM User where name=:name")).params(name='DragonFire').all() # 筛选查询列
# query的时候我们不在使用User ORM对象,而是使用User.name来对内容进行选取
# user_list = db_session.query(User.name).all()
# print(user_list)
# for row in user_list:
# print(row.name) # 别名映射 name as nick
# user_list = db_session.query(User.name.label("nick")).all()
# print(user_list)
# for row in user_list:
# print(row.nick) # 这里要写别名了 # 筛选条件格式
# user_list = db_session.query(User).filter(User.name == "DragonFire").all()
# user_list = db_session.query(User).filter(User.name == "DragonFire").first()
# user_list = db_session.query(User).filter_by(name="DragonFire").first()
# for row in user_list:
# print(row.nick) # 复杂查询
# from sqlalchemy.sql import text
# user_list = db_session.query(User).filter(text("id<:value and name=:name")).params(value=,name="DragonFire") # 查询语句
# from sqlalchemy.sql import text
# user_list = db_session.query(User).filter(text("select * from User id<:value and name=:name")).params(value=,name="DragonFire") # 排序 :
# user_list = db_session.query(User).order_by(User.id.asc()).all()
# user_list = db_session.query(User).order_by(User.id.desc()).all()
# for row in user_list:
# print(row.name,row.id) # 其他查询条件
"""
ret = session.query(User).filter_by(name='DragonFire').all()
ret = session.query(User).filter(User.id > , User.name == 'DragonFire').all()
ret = session.query(User).filter(User.id.between(, ), User.name == 'DragonFire').all() # between 大于1小于3的
ret = session.query(User).filter(User.id.in_([,,])).all() # in_([,,]) 只查询id等于1,,4的
ret = session.query(User).filter(~User.id.in_([,,])).all() # ~xxxx.in_([,,]) 查询不等于1,,4的
ret = session.query(User).filter(User.id.in_(session.query(User.id).filter_by(name='DragonFire'))).all() 子查询
from sqlalchemy import and_, or_
ret = session.query(User).filter(and_(User.id > , User.name == 'DragonFire')).all()
ret = session.query(User).filter(or_(User.id < , User.name == 'DragonFire')).all()
ret = session.query(User).filter(
or_(
User.id < ,
and_(User.name == 'eric', User.id > ),
User.extra != ""
)).all()
# select * from User where id< or (name="eric" and id>) or extra != "" # 通配符
ret = db_session.query(User).filter(User.name.like('e%')).all()
ret = db_session.query(User).filter(~User.name.like('e%')).all() # 限制
ret = db_session.query(User)[:] # 排序
ret = db_session.query(User).order_by(User.name.desc()).all()
ret = db_session.query(User).order_by(User.name.desc(), User.id.asc()).all() # 分组
from sqlalchemy.sql import func ret = db_session.query(User).group_by(User.extra).all()
ret = db_session.query(
func.max(User.id),
func.sum(User.id),
func.min(User.id)).group_by(User.name).all() ret = db_session.query(
func.max(User.id),
func.sum(User.id),
func.min(User.id)).group_by(User.name).having(func.min(User.id) >).all()
""" # ret = db_session.query(User).filter(User.id.between(, )).all() # between 大于1小于3的
# print(ret)
# ret = db_session.query(User).filter(User.id.in_([,])).all() # in_([,,]) 只查询id等于1,,4的
# ret = db_session.query(User).filter(~User.id.in_([,,])).all() # ~xxxx.in_([,,]) 查询不等于1,,4的
# print(ret) # from sqlalchemy.sql import and_, or_
#
# ret = db_session.query(User).filter(
# or_(
# User.id < ,
# and_(User.name == 'eric', User.id > ),
# User.name != ""
# ))
# print(ret) # 关闭连接
db_session.close()
七更新数据
# 更新修改数据
from sqlalchemy.orm import sessionmaker
from create_table import engine, User Session = sessionmaker(engine)
db_session = Session() # .修改数据 - 先查询预修改的数据
# update `user` set `name` = "" where id =
# res = db_session.query(User).filter(User.name=="Ywb").update({"name":"武配齐"})
# print(res)
# db_session.commit()
# db_session.close()
# res = db_session.query(User).filter(User.id >= ).update({"name":})
# print(res)
# db_session.commit()
# db_session.close()
7.1外键更新数据
# 添加数据
from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School Session = sessionmaker(engine)
db_session = Session() # 修改数据
sch = db_session.query(School).filter(School.name=="OldBoyShanghai").first()
db_session.query(Student).filter(Student.name == "小笼包").update({"school_id":sch.id})
db_session.commit()
db_session.close()
7.2补充更新
#高级版更新操作
from create_table import User,engine
from sqlalchemy.orm import sessionmaker Session = sessionmaker(engine)
db_session = Session() #直接修改
# db_session.query(User).filter(User.id > ).update({"name" : ""}) #在原有值基础上添加 -
db_session.query(User).filter(User.id > ).update({User.name: User.name + ""}, synchronize_session=False)
db_session.commit() #在原有值基础上添加 -
# db_session.query(User).filter(User.id > ).update({"age": User.age + }, synchronize_session="evaluate")
# db_session.commit()
八.多对多的表结构建立
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base() from sqlalchemy import Column,Integer,String,ForeignKey
from sqlalchemy.orm import relationship
class Girls(Base):
__tablename__ = "girl"
id = Column(Integer(),primary_key=True,autoincrement=True)
name = Column(String())
girl2boy = relationship("Boy",secondary="Hote",backref="boy2girl") class Boy(Base):
__tablename__ ="boy"
id = Column(Integer(),primary_key=True,autoincrement=True)
name = Column(String()) class Hote(Base):
__tablename__ ="hote"
id = Column(Integer(),primary_key=True,autoincrement=True)
name = Column(String())
girl_id = Column(Integer, ForeignKey("girl.id"))
boy_id = Column(Integer, ForeignKey("boy.id"))
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/day127?charset=utf8") Base.metadata.create_all(engine)
8.1多对多的增加数据
from sqlalchemy.orm import sessionmaker
from app.M2m import engine
Session = sessionmaker(engine) db_session = Session()
#.增加
# .通过Boy添加Girl和Hotel数据
boy = Boy(name="DragonFire")
boy.girl2boy = [Girls(name="赵丽颖"),Girls(name="Angelababy")]
db_session.add(boy)
db_session.commit() # .通过Girl添加Boy和Hotel数据
girl = Girls(name="珊珊")
girl.boys = [Boy(name="Dragon")]
db_session.add(girl)
db_session.commit()
8.2多对多的查询数据
from my_M2M import Girl,Boy,Hotel,engine # 创建连接
from sqlalchemy.orm import sessionmaker
# 创建数据表操作对象 sessionmaker
DB_session = sessionmaker(engine)
db_session = DB_session() # .通过Boy查询约会过的所有Girl
hotel = db_session.query(Boy).all()
for row in hotel:
for row2 in row.girl2boy:
print(row.name,row2.name) # .通过Girl查询约会过的所有Boy
hotel = db_session.query(Girl).all()
for row in hotel:
for row2 in row.boys:
print(row.name,row2.name)
SQLAlcvchem的更多相关文章
随机推荐
- 用python 获取照片的Exif 信息(获取拍摄设备,时间,地点等信息)
第一步:先安装 pip install exifread 第二部:上代码 import exifread import requests class PhotoExifInfo(): def __in ...
- 问题:Thymeleaf整合Spring Security后sec属性不起作用
可能原因: 版本不兼容,例如2.1.x的SpringBoot不兼容3.0.4的thymeleaf-extras-springsecurity4 解决方案: 修改Spring Boot的版本为2.0.x ...
- centos7 mysql 各种报错
1.重置root密码 vi /etc/my.cnf 添加skip-grant-tables service mysqld restart 2.mysql 登录 报错1 Unknown system v ...
- 这样讲 SpringBoot 自动配置原理,你应该能明白了吧
https://juejin.im/post/5ce5effb6fb9a07f0b039a14 前言 小伙伴们是否想起曾经被 SSM 整合支配的恐惧?相信很多小伙伴都是有过这样的经历的,一大堆配置问题 ...
- 【ESXI6.0】 ESXI6.0安装时无法安装网卡驱动的解决方法及将网卡驱动加载进ISO
http://blog.163.com/xifanliang@yeah/blog/static/115078488201571584321787/ 若安装时提示如下图所示 之后安装无法完成,会提示没有 ...
- 关于myBatis配置中的一些注意事项
最近在学习mybatis,在网上查阅资料,并按照别人的范例来测试,总会出一些错误,这里把配置过程中的一些注意事项梳理一下. 一.导包(用eclipse开发) 1.如果你新建的是普通的project,需 ...
- 使用 Maven Profile 和 Filtering 打各种环境的包(转)
http://tunzao.me/articles/maven-profile/ https://blog.csdn.net/syani/article/details/52237470
- Windows 7、Windows XP SP3关闭DEP堆栈执行保护
Windows XP SP3 在Windows XP SP3中,关闭DEP的方法是: 编辑C:\boot.ini,你大概会看到如下内容 [boot loader] timeout=30 default ...
- 风控MIS那些事
信贷风险管理应基于数据进行决策,MIS则是通过对数据的加工与展示,给决策者提供参考. 管理信息系统(ManagementInformation System,MIS)是进行信息的 收集.传输.加工.储 ...
- pyqt5-复合控件中的子控件
天子骄龙