当前位置:网站首页>[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_
边栏推荐
- 美团二面:为什么 Redis 会有哨兵?
- Compilation of libwebsocket
- 51单片机进修的一些感悟
- Single chip microcomputer realizes modular programming: Thinking + example + system tutorial (the degree of practicality is appalling)
- Cooperative development in embedded -- function pointer
- Global and Chinese market for annunciator panels 2022-2028: Research Report on technology, participants, trends, market size and share
- 嵌入式開發中的防禦性C語言編程
- Research and implementation of hospital management inpatient system based on b/s (attached: source code paper SQL file)
- MapReduce instance (VIII): Map end join
- Mapreduce实例(七):单表join
猜你喜欢

Mapreduce实例(七):单表join

Lua script of redis

MapReduce instance (IV): natural sorting

【深度学习】语义分割:论文阅读:(CVPR 2022) MPViT(CNN+Transformer):用于密集预测的多路径视觉Transformer

Nc17 longest palindrome substring

What are the models of data modeling

【深度學習】語義分割-源代碼匯總

Research and implementation of hospital management inpatient system based on b/s (attached: source code paper SQL file)

I2C summary (single host and multi host)

运维,放过监控-也放过自己吧
随机推荐
基于B/S的网上零食销售系统的设计与实现(附:源码 论文 Sql文件)
Keep these four requirements in mind when learning single chip microcomputer with zero foundation and avoid detours
Global and Chinese markets for hardware based encryption 2022-2028: Research Report on technology, participants, trends, market size and share
【深度学习】语义分割:论文阅读(NeurIPS 2021)MaskFormer: per-pixel classification is not all you need
Take you back to spark ecosystem!
Summary of May training - from a Guang
CAPL 脚本打印函数 write ,writeEx ,writeLineEx ,writeToLog ,writeToLogEx ,writeDbgLevel 你真的分的清楚什么情况下用哪个吗?
为拿 Offer,“闭关修炼,相信努力必成大器
为什么要数据分层
Mapreduce实例(五):二次排序
[deep learning] semantic segmentation: paper reading: (CVPR 2022) mpvit (cnn+transformer): multipath visual transformer for dense prediction
英雄联盟轮播图自动轮播
Workflow - activiti7 environment setup
Programmation défensive en langage C dans le développement intégré
Nc17 longest palindrome substring
大学想要选择学习自动化专业,可以看什么书去提前了解?
068. Find the insertion position -- binary search
嵌入式开发比单片机要难很多?谈谈单片机和嵌入式开发设计经历
Hard core! One configuration center for 8 classes!
How can I take a shortcut to learn C language in college