Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Python-sqlalchemy

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

From sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column,Integer,Stringfrom sqlalchemy.orm import sessionmakerfrom sqlalchemy import funcengine=create_engine ("mysql+pymysql://root:123456@localhost/mxm_db", encoding='utf-8',echo=False) Base=declarative_base () # generates the orm base class class User (Base): _ _ tablename__='user' id=Column (Integer) Primary_key=True) name=Column (String (32)) password=Column (String (64)) def _ _ repr__ (self): return'% (self.id,self.name,self.password) Base.metadata.create_all (engine) Session_class=sessionmaker (bind=engine) # create session with database classSession=Session_class () # generate session instance Same as cursor # 1. Add data # user_obj=User (name='mxm1',password='mxm1') # generate the data object you want to create # print (user_obj.name,user_obj.password) # Session.add (user_obj) # add the data object to this session # Session.commit () # submit and create data # 2. Query data data=Session.query (User). Filter_by (name='mxm1'). First () # query does not require commitprint (data) # 3. Modify data # data.name='mxm2'#data.password='mxm2'#Session.commit () # 4. Data rollback # Session.rollback () # filter (User.name.in_ (['name1','name2'])) # 5. Statistics # data=Session.query (User). Filter_by (password='mxm').\ # filter_by (name='mxm'). Count () # query does not require commit#print (data) # 6. Group # data=Session.query (User.name,func.count (User.name)). Group_by (User.name). All () # print (data)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report