当前位置:网站首页>[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_
边栏推荐
- Learning SCM is of great help to society
- Use of activiti7 workflow
- Selection of software load balancing and hardware load balancing
- leetcode-14. Longest common prefix JS longitudinal scanning method
- Global and Chinese market of appointment reminder software 2022-2028: Research Report on technology, participants, trends, market size and share
- May brush question 01 - array
- 大学想要选择学习自动化专业,可以看什么书去提前了解?
- MapReduce instance (VII): single table join
- 在CANoe中通过Panel面板控制Test Module 运行(高级)
- Global and Chinese markets for modular storage area network (SAN) solutions 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢

MapReduce instance (V): secondary sorting

What are the models of data modeling

Regular expressions are actually very simple

Interview shock 62: what are the precautions for group by?

Publish and subscribe to redis

Teach you how to write the first MCU program hand in hand

Nc17 longest palindrome substring

Listen to my advice and learn according to this embedded curriculum content and curriculum system

C#/. Net phase VI 01C Foundation_ 01: running environment, process of creating new C program, strict case sensitivity, meaning of class library

Mapreduce实例(五):二次排序
随机推荐
VH6501学习系列文章
How can I take a shortcut to learn C language in college
嵌入式中的合作开发--函数指针
Publish and subscribe to redis
33岁可以学PLC吗
工作流—activiti7环境搭建
Global and Chinese markets for modular storage area network (SAN) solutions 2022-2028: Research Report on technology, participants, trends, market size and share
五月刷题02——字符串
MapReduce instance (VIII): Map end join
《ASP.NET Core 6框架揭秘》样章发布[200页/5章]
Single chip microcomputer realizes modular programming: Thinking + example + system tutorial (the degree of practicality is appalling)
[untitled]
June brush question 02 - string
Can I learn PLC at the age of 33
The real future of hardware engineers may not be believed by you if I say so
Hero League rotation map automatic rotation
In order to get an offer, "I believe that hard work will make great achievements
MySQL数据库优化的几种方式(笔面试必问)
Mapreduce实例(六):倒排索引
学习单片机对社会的帮助是很大的