一.安装(稳定版的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的更多相关文章

随机推荐

  1. 在springboot中使用拦截器

    在springMVC中可以实现拦截器,是通过实现HandlerInterceptor接口,然后在springmvc-web.xml中配置就可以使用拦截器了.在springboot中拦截器也是一样的思想 ...

  2. java 过滤器filter使用案例

    主要需要 过滤器类  和配置文件 1.过滤器类 SessionFilter package com.service; import javax.servlet.*; import javax.serv ...

  3. python-函数4(递归、高阶函数)

    python-函数4(递归.高阶函数) 递归 在函数内部,可以调用其他函数.如果一个函数在内部调用自身本身,这个函数就是递归函数. 递归特性: 1. 递归必须有一个明确的结束条件 2. 每次进入更深一 ...

  4. 自动化监控软件之zabbix安装

    自动化监控系统 cacti : 基于snmp(简单的网络管理协议)协议的监控软件,强大的绘图软件 缺点: 自带的监控模板比较少,不能默认 自带监控报警功能(只能自己去官网下载模板) Nagios: 插 ...

  5. python中对RSA的加密和解密

    首先,生成一对密钥,并保存 def create_keys(): # 生成公钥和私钥 (pubkey, privkey) = rsa.newkeys(1024) pub = pubkey.save_p ...

  6. jenkins复选框插件Extended Choice Parameter plugin

    转载 https://www.cnblogs.com/zndxall/p/9512059.html https://www.cnblogs.com/jwentest/p/7113399.html

  7. iOS控件圆角与半圆角

    开发过程中难免用到圆角以及恶心的半圆角,看代码 半圆角:这是把左边的两个角切成了圆角 UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoun ...

  8. java中list和map详解

    一.概叙 List , Set, Map都是接口,前两个继承至Collection接口,Map为独立接口, List下有ArrayList,Vector,LinkedList Set下有HashSet ...

  9. linux 环境下安装MySQL5.7(yum)

    安装环境: CentOS7 64位,MySQL5.7 原文链接:https://blog.csdn.net/xyang81/article/details/51759200 1. 配置yum源 在My ...

  10. TF-epoch、 iteration和batchsize区别(转载)

    from http://www.cnblogs.com/qggg/p/6876942.html 转自 http://blog.csdn.net/sinat_30071459/article/detai ...