当前位置:网站首页>sqlalchemy的基本使用
sqlalchemy的基本使用
2022-06-29 01:11:00 【ch_atu】
依赖
pip install sqlalchemy
基本使用
from sqlalchemy.orm import Session, sessionmaker, declarative_base
from sqlalchemy import create_engine, Column, Integer, String
# 1.创建引擎
engine = create_engine('mysql+pymysql://root:[email protected]/sqlalchemy_test')
# 2.创建会话
# 2.1 基本创建方式
# s = Session(bind=engine)
# 2.2 通过sessionmaker创建,本质上还是Session,只是可自定义配置强
# Session = sessionmaker(bind=engine)
# s = Session()
# 2.3 通过scoped_session创建, 传入一个session工厂
Session =scoped_session(sessionmaker(bind=engine))
s = Session()
# 3.创建ORM映射基类
Base = declarative_base()
# 4.创建数据表
class User(Base):
__tablename__ = 'user_account'
id = Column(Integer, primary_key=True)
name = Column(String(25))
def __repr__(self):
return f'User(id={
self.id}, name={
self.name})'
# 5.不存在则创建,存在则不创建
Base.metadata.create_all(engine)
# 6.实例化一个Use对象
# user = User(name='chatu')
# 7.将User对象添加到Session中
s.add(user)
# 8.提交到数据库
s.commit()
# 9.关闭session对象
s.close()
更多数据库操作
from add import s, User, engine # 这边导入的是上方定义的
from sqlalchemy import select, table, update, insert, delete, create_engine, column
# result = s.query(User).all()
# print(result)
# s.scalars()执行语句,并返回一个个实例对象
# 可以通过select这种原生的,然后去执行
# 也可以通过session.query去筛选
# s.execute()可以执行增删改查
# ##### 接近原生的sqlalchemy查询
print(type(select(User)))
# 查找
sel = select(User).where(User.name == 'chatu1')
print(type(select(User).where(User.name == 'chatu1')))
result = s.execute(sel)
print(result, '=============', type(result))
for i in result:
print(i)
print('---------------------',s.scalars(sel))
for i in s.scalars(sel):
print(i)
# 更新
upd = (update(User).
where(User.id == 4).
values(name='chst1122')
)
# 直接通过engine创建的连接则在执行execute的时候就会提交到数据库
# conn = engine.connect()
# conn.execute(upd)
# 通过session执行execute
a = s.execute(upd) # 执行更新
s.commit() # 只有提交之后数据库才会更新
# 插入
ins = insert(User).values(name='hello world')
s.execute((ins))
s.commit()
# 删除
delete_data = delete(User).where(column('id') >= 100)
s.execute(delete_data)
s.commit()
###### 使用会话机制查询
# 查询
filter_query = s.query(User).filter(User.name=='chatu1').all() # 返回一个列表,包含所有筛选对象
# filter_query = s.query(User).filter(User.name.in_(['chatu2'])).all() # 返回一个列表,包含所有筛选对象
print(filter_query)
# 修改
update_filter = s.query(User).filter(User.name=='chatu1').update({
'name':'chatu11'})
s.commit()
# 添加
user = User(name='hello chatu')
s.add(user)
s.commit()
# 删除
s.query(User).filter(User.name=='chst1122').delete()
s.commit()
附录
1.链接:Session、sessionmaker、scoped_session相关资料
2.接近原生的sqlalchemy操作
链接-查询:sqlalchemy-查询
链接-更新,插入,删除:sqlalchemy-更新,插入,删除
3.会话通过query操作数据库的操作
会话的query查询:query操作API
边栏推荐
- EasyCVR服务private.pem文件被清空,导致无法正常启动该如何处理?
- 使用.Net驱动Jetson Nano的OLED显示屏
- 198. house raiding
- Redis common command manual
- Successfully solved (machine learning data segmentation problem): modulenotfounderror: no module named 'sklearn cross_ validation‘
- [image enhancement] manual multiple exposure fusion amef image defogging based on MATLAB [including Matlab source code 1916]
- What is redis
- Check the open source projects of yyds in June!
- Werewolf kill casual game wechat applet template source code / wechat game source code
- Large-scale case applications to developing post-click conversion rate estimation with MTL
猜你喜欢

Seven mistakes in IT Governance and how to avoid them

Cocoscrreator dynamically switches skeletondata to update bones

Successfully solved (machine learning data segmentation problem): modulenotfounderror: no module named 'sklearn cross_ validation‘

What is contemporaneous group analysis? Teach you to use SQL to handle

Interviewer: with the for loop, why do you need foreach??

GUI Graphical user interface programming example - color selection box

统计学习方法(2/22)感知机

What is the difference between the history and Western blotting

Advanced Installer Architect创作工具

狼人杀休闲游戏微信小程序模板源码/微信小游戏源码
随机推荐
Sword finger offer 14- I. cut rope
[eight part essay] MySQL
致我们曾经遇到过的接口问题
linux7(centos7)设置oracle11开机自启动
If you can play these four we media operation tools, the sideline income of 6000+ is very easy
Day 8 script and audio
[MCU club] design of GSM version of range hood based on MCU [simulation design]
Two ways to set up a single Nacos load balancing ribbon polling policy weight
EasyCVR接入Ehome协议的设备,无法观看设备录像是什么原因?
Accessories and working process of machine vision system
After easycvr creates a new user, the video access page cannot be clicked. Fix the problem
数据库-优化器
3D, point cloud splicing
EasyCVR集群版本替换成老数据库造成的服务崩溃是什么原因?
Seven mistakes in IT Governance and how to avoid them
EdrawMax思维导图,EdrawMax组织结构图
利用kubernetes资源锁完成自己的HA应用
Redis是什么
Is it safe to open a securities account at qiniu business school in 2022?
企业和IT领导者对创新的误解