当前位置:网站首页>[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_
边栏推荐
- Global and Chinese market for annunciator panels 2022-2028: Research Report on technology, participants, trends, market size and share
- Full stack development of quartz distributed timed task scheduling cluster
- 单片机如何从上电复位执行到main函数?
- Processes of libuv
- MapReduce instance (IV): natural sorting
- 机械工程师和电气工程师方向哪个前景比较好?
- Hero League rotation map automatic rotation
- Cap theory
- CAPL脚本中关于相对路径/绝对路径操作的几个傻傻分不清的内置函数
- 工作流—activiti7环境搭建
猜你喜欢

Release of the sample chapter of "uncover the secrets of asp.net core 6 framework" [200 pages /5 chapters]

Programmation défensive en langage C dans le développement intégré

Oom happened. Do you know the reason and how to solve it?

MapReduce instance (VII): single table join

MapReduce working mechanism

Lua script of redis

学习单片机对社会的帮助是很大的

为拿 Offer,“闭关修炼,相信努力必成大器

Compilation of libwebsocket

How can I take a shortcut to learn C language in college
随机推荐
六月刷题01——数组
MapReduce工作机制
Publish and subscribe to redis
大学C语言入门到底怎么学才可以走捷径
Release of the sample chapter of "uncover the secrets of asp.net core 6 framework" [200 pages /5 chapters]
Nc29 search in two-dimensional array
tn-c为何不可用2p断路器?
Global and Chinese market of linear regulators 2022-2028: Research Report on technology, participants, trends, market size and share
Segmentation sémantique de l'apprentissage profond - résumé du code source
Keep these four requirements in mind when learning single chip microcomputer with zero foundation and avoid detours
基于B/S的网上零食销售系统的设计与实现(附:源码 论文 Sql文件)
大学想要选择学习自动化专业,可以看什么书去提前了解?
Vs All comments and uncomments
五月刷题27——图
018.有效的回文
What you have to know about network IO model
Why data Tiering
June brush question 01 - array
Global and Chinese market of bank smart cards 2022-2028: Research Report on technology, participants, trends, market size and share
I2C summary (single host and multi host)