当前位置:网站首页>[flask] crud addition and query operation of data
[flask] crud addition and query operation of data
2022-07-06 09:46:00 【YZL40514131】
use session Add, delete, modify and query data :
1、 Create model classes , Generate data table
# First step : Create base class
Base=declarative_base(engine)
# The second step : Definition python Mapping of classes and tables
class Person(Base):
__tablename__='t_person' # Create table name , It is best to t_ start
id=Column(name='id',type_=Integer,primary_key=True,autoincrement=True)
name=Column(name='name',type_=String(255))
age=Column(name='age',type_=Integer)
address=Column(name='address',type_=String(255))
country=Column(name='country',type_=String(50)) # New fields added after the table is created
city=Column(name='city',type_=String(50)) # New fields added after the table is created
def __str__(self):
return ' full name :{}- Annual collar :{}- Address :{}- Country :{}- City :{}'.format(self.name,self.age,self.address,self.country,self.city)
# The third step : Model classes create tables
#Base.metadata.drop_all()
Base.metadata.create_all()
2、 structure session object :
All and database ORM All operations must pass through a process called session To implement ,
Get the session object through the following code :
from sqlalchemy.orm import sessionmaker
engine = create_engine(DB_URI)
Base = declarative_base(engine)
session = sessionmaker(engine)() # Be careful , Returns a function
Particular attention 1:session = sessionmaker(engine)() Returns a function
3、 Add data (C)
Add a piece of data
# Create objects , That is, create a piece of data :
p1=Person(name='zz',age=20,address=' Fengtai District ',country=' China ',city=' Beijing ')
# Add this object to `session` In the session object :
session.add(p1)
# take session The objects in do commit operation ( Submit )
session.commit()
Add multiple pieces of data at one time
# Add data to database
p1=Person(name='django',age=17,address=' Fengtai District ',country=' China ',city=' Beijing ')
p2=Person(name='kb',age=21,address=' Daxing District ',country=' China ',city=' Beijing ')
p3=Person(name='python',age=18,address=' Changping District ',country=' China ',city=' Beijing ')
p4=Person(name='flask',age=25,address=' Haidian District ',country=' China ',city=' Beijing ')
session.add_all([p1,p2,p3,p4])
session.commit()
4、 Find data
1、 Find all the data in the table corresponding to the model
all_person=session.query(Person).all()
for person in all_person:
print(person)
full name :zz- Annual collar :20- Address : Fengtai District - Country : China - City : Beijing
full name :django- Annual collar :17- Address : Fengtai District - Country : China - City : Beijing
full name :kb- Annual collar :21- Address : Daxing District - Country : China - City : Beijing
full name :python- Annual collar :18- Address : Changping District - Country : China - City : Beijing
full name :flask- Annual collar :25- Address : Haidian District - Country : China - City : Beijing
2、 Use first Method to get the first data in the result set
p1=session.query(Person).first()
print(p1)
full name :zz- Annual collar :20- Address : Fengtai District - Country : China - City : Beijing
3、 Use filter To do condition query
for example : The inquiry year is 20 People over years old
p2=session.query(Person).filter(Person.age>20)
print(p2)
Print the results : It's a piece. sql sentence
SELECT t_person.id AS t_person_id, t_person.name AS t_person_name, t_person.age AS t_person_age, t_person.address AS t_person_address, t_person.country AS t_person_country, t_person.city AS t_person_city
FROM t_person
WHERE t_person.age > %(age_1)s
Be careful 2: Just add first,all Function will return specific data , Otherwise, only print out sql sentence
p3=session.query(Person).filter(Person.age>20).all()
for p in p3:
print(p)
full name :kb- Annual collar :21- Address : Daxing District - Country : China - City : Beijing
full name :flask- Annual collar :25- Address : Haidian District - Country : China - City : Beijing
4、 Use filter_by To do condition query
p4=session.query(Person).filter_by(age=20).all()
for p in p4:
print(p)
full name :zz- Annual collar :20- Address : Fengtai District - Country : China - City : Beijing
5、 ... and 、filter Filter conditions :
Filtering is a very important function of data extraction , Here are some common filter conditions to explain , And these filter conditions can only pass through filter Method :
Particular attention 3:filter: Use model class name . Property name ==' Property value ’ Filter queries
1.equals :
Query name python Your character information
p5=session.query(Person).filter(Person.name=='python').all()
print(p5)
2.not equals : !
The query name is not flask Your character information
p6=session.query(Person).filter(Person.name!='flask').all()
print(p6)
3.like & ilike [ Case insensitive ]:
The query name contains an Your character information
p7=session.query(Person).filter(Person.name.like('%an%')).all()
print(p7)
4. in_:
The query area is the person information under Haidian District and Changping District
p8=session.query(Person).filter(Person.address.in_([' Changping District ',' Haidian District '])).all()
print(p8)
5. not in:
The query area is not the task information under Haidian District and Changping District
p9=session.query(Person).filter(~Person.address.in_([' Changping District ',' Haidian District '])).all()
print(p9)
6. is null:
The query annual income is None Your character information
p10=session.query(Person).filter(Person.age==None).all()
print(p10)
perhaps
p11=session.query(Person).filter(Person.age.is_(None)).all()
print(p11)
7. is not null:
The query annual income is not None Your character information
p12=session.query(Person).filter(Person.age!=None).all()
print(p12)
p13=session.query(Person).filter(Person.age.isnot(None)).all()
print(p13)
8. and_:
The search name is python, And the annual income is 20 Year old character information
p14=session.query(Person).filter(Person.name=='python',Person.age=='20').all()
print(p14)
perhaps
p15 = session.query(Person).filter(and_(Person.name == 'python', Person.age == '20')).all()
print(p15)
perhaps
p16= session.query(Person).filter(Person.name == 'python').filter(Person.age=='20').all()
print(p16)
9. or_:
The search name is python, Or the annual income is 18 Year old character information
p17=session.query(Person).filter(or_(Person.name=='python',Person.age=='20')).all()
print(p17)
Particular attention 4: above and_、or_ All need to import
from sqlalchemy import and_,or_
边栏推荐
- [Yu Yue education] reference materials of power electronics technology of Jiangxi University of science and technology
- Mapreduce实例(八):Map端join
- The real future of hardware engineers may not be believed by you if I say so
- CAP理论
- 单片机如何从上电复位执行到main函数?
- leetcode-14. Longest common prefix JS longitudinal scanning method
- CANoe仿真功能之自动化序列(Automation Sequences )
- 嵌入式开发比单片机要难很多?谈谈单片机和嵌入式开发设计经历
- Nc17 longest palindrome substring
- O & M, let go of monitoring - let go of yourself
猜你喜欢
随机推荐
五月刷题01——数组
Oom happened. Do you know the reason and how to solve it?
[deep learning] semantic segmentation: thesis reading (neurips 2021) maskformer: per pixel classification is not all you need
max-flow min-cut
Yarn organizational structure
英雄联盟轮播图自动轮播
六月刷题02——字符串
Leetcode:608 tree node
Mapreduce实例(五):二次排序
Why can't TN-C use 2p circuit breaker?
33岁可以学PLC吗
为什么要数据分层
CANoe仿真功能之自动化序列(Automation Sequences )
Une grande vague d'attaques à la source ouverte
Scoped in webrtc_ refptr
嵌入式開發中的防禦性C語言編程
《ASP.NET Core 6框架揭秘》样章发布[200页/5章]
Activiti7工作流的使用
Global and Chinese market of cup masks 2022-2028: Research Report on technology, participants, trends, market size and share
一文读懂,DDD落地数据库设计实战