当前位置:网站首页>[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_
边栏推荐
- Mapreduce实例(六):倒排索引
- In order to get an offer, "I believe that hard work will make great achievements
- Day 5 of MySQL learning
- CAPL脚本中关于相对路径/绝对路径操作的几个傻傻分不清的内置函数
- Design and implementation of online snack sales system based on b/s (attached: source code paper SQL file)
- Hero League rotation chart manual rotation
- 面试突击62:group by 有哪些注意事项?
- Why is 51+ assembly in college SCM class? Why not come directly to STM32
- 运维,放过监控-也放过自己吧
- O & M, let go of monitoring - let go of yourself
猜你喜欢
解决小文件处过多
Popularization of security knowledge - twelve moves to protect mobile phones from network attacks
[deep learning] semantic segmentation: thesis reading (neurips 2021) maskformer: per pixel classification is not all you need
Keep these four requirements in mind when learning single chip microcomputer with zero foundation and avoid detours
Mapreduce实例(六):倒排索引
tn-c为何不可用2p断路器?
Une grande vague d'attaques à la source ouverte
Single chip microcomputer realizes modular programming: Thinking + example + system tutorial (the degree of practicality is appalling)
Elk project monitoring platform deployment + deployment of detailed use (II)
CANoe的数据回放(Replay Block),还是要结合CAPL脚本才能说的明白
随机推荐
基于B/S的医院管理住院系统的研究与实现(附:源码 论文 sql文件)
How can I take a shortcut to learn C language in college
Redis connection redis service command
Day 5 of MySQL learning
Vs All comments and uncomments
零基础学习单片机切记这四点要求,少走弯路
为什么要数据分层
Selection of software load balancing and hardware load balancing
Global and Chinese markets for hardware based encryption 2022-2028: Research Report on technology, participants, trends, market size and share
018. Valid palindromes
一大波開源小抄來襲
Counter attack of noodles: redis asked 52 questions in a series, with detailed pictures and pictures. Now the interview is stable
Leetcode:608 树节点
Processes of libuv
【深度學習】語義分割-源代碼匯總
33岁可以学PLC吗
Global and Chinese market of cup masks 2022-2028: Research Report on technology, participants, trends, market size and share
May brush question 03 - sorting
Function description of shell command parser
Mapreduce实例(九):Reduce端join