当前位置:网站首页>Basic use of Sqlalchemy
Basic use of Sqlalchemy
2022-06-29 01:15:00 【ch_ atu】
rely on
pip install sqlalchemy
Basic use
from sqlalchemy.orm import Session, sessionmaker, declarative_base
from sqlalchemy import create_engine, Column, Integer, String
# 1. Create the engine
engine = create_engine('mysql+pymysql://root:[email protected]/sqlalchemy_test')
# 2. Create a session
# 2.1 Basic creation method
# s = Session(bind=engine)
# 2.2 adopt sessionmaker establish , In essence Session, It's just that you can customize the configuration
# Session = sessionmaker(bind=engine)
# s = Session()
# 2.3 adopt scoped_session establish , Pass in a session factory
Session =scoped_session(sessionmaker(bind=engine))
s = Session()
# 3. establish ORM Mapping base class
Base = declarative_base()
# 4. Create data table
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. Create if it does not exist , If it exists, it doesn't create
Base.metadata.create_all(engine)
# 6. Instantiate a Use object
# user = User(name='chatu')
# 7. take User Object added to Session in
s.add(user)
# 8. Commit to database
s.commit()
# 9. close session object
s.close()
More database operations
from add import s, User, engine # What is imported here is defined above
from sqlalchemy import select, table, update, insert, delete, create_engine, column
# result = s.query(User).all()
# print(result)
# s.scalars() Execute statement , And return instance objects
# Can pass select This kind of native , Then go ahead and do
# It can also be done through session.query To screen
# s.execute() You can add, delete, modify and query
# ##### Near native sqlalchemy Inquire about
print(type(select(User)))
# lookup
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)
# to update
upd = (update(User).
where(User.id == 4).
values(name='chst1122')
)
# Directly through engine The created connection is executing execute Will be submitted to the database
# conn = engine.connect()
# conn.execute(upd)
# adopt session perform execute
a = s.execute(upd) # Perform the update
s.commit() # The database will not be updated until it is committed
# Insert
ins = insert(User).values(name='hello world')
s.execute((ins))
s.commit()
# Delete
delete_data = delete(User).where(column('id') >= 100)
s.execute(delete_data)
s.commit()
###### Use the session mechanism to query
# Inquire about
filter_query = s.query(User).filter(User.name=='chatu1').all() # Return a list , Include all filtered objects
# filter_query = s.query(User).filter(User.name.in_(['chatu2'])).all() # Return a list , Include all filtered objects
print(filter_query)
# modify
update_filter = s.query(User).filter(User.name=='chatu1').update({
'name':'chatu11'})
s.commit()
# add to
user = User(name='hello chatu')
s.add(user)
s.commit()
# Delete
s.query(User).filter(User.name=='chst1122').delete()
s.commit()
appendix
1. link :Session、sessionmaker、scoped_session Related information
2. Near native sqlalchemy operation
link - Inquire about :sqlalchemy- Inquire about
link - to update , Insert , Delete :sqlalchemy- to update , Insert , Delete
3. Conversation through query The operation of the operation database
The session query Inquire about :query operation API
边栏推荐
- How to handle a SIGTERM - how to handle a SIGTERM
- Getting started with SQL
- Different subsequence problems I
- 【图像处理】基于matlab实现图像曲线调整系统
- Depth first search to realize the problem of catching cattle
- To the interface problems we have encountered
- [staff] pedal mark (step on pedal ped mark | release pedal * mark | corresponding pedal command in MIDI | continuous control signal | switch control signal)
- Esmm reading notes
- GUI Graphical user interface programming example - color selection box
- 我想今天买股票,可以么?现在网上开户安全么?
猜你喜欢
[Architect (Part 38)] locally install the latest version of MySQL database developed by the server

Exclusive analysis | about resume and interview

多维分析预汇总应该怎样做才管用?

致我们曾经遇到过的接口问题

Advanced Installer Architect创作工具

Check the open source projects of yyds in June!
UI高度自适应的修改方案

【图像增强】基于matlab人工多重曝光融合AMEF图像去雾【含Matlab源码 1916期】

Mask wearing face data set and mask wearing face generation method

Ensemble de données sur les visages masqués et méthode de génération des visages masqués
随机推荐
戴口罩人臉數據集和戴口罩人臉生成方法
XML and other file contents in idea cannot be highlighted, and the file becomes gray
【图像增强】基于matlab人工多重曝光融合AMEF图像去雾【含Matlab源码 1916期】
【架构师(第三十八篇)】 服务端开发之本地安装最新版 MySQL 数据库
What is the reason for the service crash caused by replacing the easycvr cluster version with the old database?
How to handle a SIGTERM - how to handle a SIGTERM
Qt est basé sur le système de gestion RFID (peut être appliqué à la plupart des systèmes de gestion RFID)
Pytorch -- use and modification of existing network model
如何进行数据库选型
不同的子序列问题I
有了这款工具,自动化识别验证码再也不是问题
我想今天买股票,可以么?现在网上开户安全么?
[RRT 3D path planning] rapid expansion of random tree UAV 3D path planning based on MATLAB [including Matlab source code phase 1914]
[image enhancement] manual multiple exposure fusion amef image defogging based on MATLAB [including Matlab source code 1916]
IPFS简述
Uvm:field automation mechanism
[MCU club] design of GSM version of range hood based on MCU [physical design]
How to mount FSS object storage locally
深度优先搜索实现抓牛问题
How can multidimensional analysis pre summary work?