时间:2021-07-01 10:21:17 帮助过:24人阅读
import sqlalchemy from sqlalchemy import create_engine from sqlalchemy import Column,Integer,String from sqlalchemy import and_,or_ from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/t1") Base = declarative_base()#生成一个SQLORM基类 class User(Base): __tablename__ = "users" id = Column(Integer,primary_key=True,autoincrement=True) name = Column(String(40)) fullname = Column(String(40)) password = Column(String(40)) def __repr__(self): return "<User(name=‘%s‘, fullname=‘%s‘,password=‘%s‘)>"%(self.name,self.fullname,self.password) Base.metadata.create_all(engine)#创建所有表结构 #Base.metadata.drop_all(engine)#删除所有的表 ed_user = User(name=‘xiaoyu‘,fullname=‘xiaoudaf‘,password=‘123‘) MySession = sessionmaker(bind=engine) session=MySession() #一次加入一条 # session.add(ed_user) #一次加入多条 # session.add_all([ # User(name=‘daf‘,fullname=‘fafwaf‘,password=‘fwa‘), # User(name=‘daf‘, fullname=‘fafwaf‘, password=‘fwa‘), # User(name=‘daf‘, fullname=‘fafwaf‘, password=‘fwa‘), # ]) # # session.commit() #查询所有 print(session.query(User).all()) #按顺序查询 for row in session.query(User).order_by(User.id): print(row) #进行过滤 for row in session.query(User).filter(User.name.in_([‘xiaoyu‘,])): print(row) for row in session.query(User).filter(~User.name.in_([‘xiaoyu‘, ])): print(row) for row in session.query(User).filter(User.name==‘xiaoyu‘): print(row) print(session.query(User).filter(User.name==‘xiaoyu‘).count()) for row in session.query(User).filter(and_(User.name==‘daf‘,User.fullname==‘fafwafs‘)): print(row) for row in session.query(User).filter(or_(User.name==‘daf‘,User.fullname==‘xiaoudafc‘)): print(row)
西游之路——python全栈——ORM之SQLAlchemy(1)
标签:ssi tab 执行sql 127.0.0.1 对象 dia 代码 配置 结构