''' sqlalchemy 操作数据库--增删改查 ''' from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('mysql+pymysql://chen:123456@192.168.4.10/sqlalchemy') DBsession = sessionmaker(bind=engine) session = DBsession() Base = declarative_base() #类对应数据库中的表字段,一个实例就是一行数据 class Student(Base): __tablname__ = "student" id = Column(Integer,primary_key=True) name = Column(String(50)) age = Column(Integer) address = Column(String(50)) #insert 增 st1 = Student(id=1001,name='ling',age=25,address='BeiJing') st2 = Student(id=1002,name='molin',age=18,address='shanghai') st3 = Student(id=1003,name='cc',age=23,address='zhuhai') st4 = Student(id=1004,name='lieeeeng',age=32,address='hangzhou') session.add_all([st1,st2,st3,st4]) session.commit() #select查 a = session.query(Student).filter_by(name="ling").first() print(a) print(a.id) print(a.name) print(a.age) print(a.address) ''' filter_by 和 filter filter_by(name="ling") 不能使用 > < = filter(Student.id>1001) 必须使用 Student.id 可以使用 > < = ''' a = session.query(Student).filter(Student.id>1001).all() for i in a: print(i.id) print(i.name) print(i.age) print(i.sex) print(i.address)
转载于:https://my.oschina.net/u/3824134/blog/1811608