Python SQLALchemy框架 (5)

   如果一条查询语句是以filter结尾,则返回结果对象的__str__方法中都是SQL语句:

result = session.query(Teachers).filter() print(result) # SELECT teachers.id AS teachers_id, teachers.name AS teachers_name # FROM teachers

   如果是all结尾,返回的就是一个列表,first结尾也是一个列表:

result = session.query(Teachers).all() print(result) # [<models.Teachers object at 0x00000178EB0B5550>, <models.Teachers object at 0x00000178EB0B5518>, <models.Teachers object at 0x00000178EB0B5048>] 执行SQL语句

   执行原生SQL:

from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker # 导入引擎,模型表等 from models import * # 通过Session绑定引擎和数据库建立关系 Session = sessionmaker(bind=engine) # 创建链接池,使用session即可为当前线程拿出一个链接对象。内部采用threading.local进行隔离 session = scoped_session(Session) cursor = session.execute(r"select * from students where id <= (:num)",params={"num":2}) print(cursor.fetchall()) # 提交 session.commit() # 关闭链接 session.close()

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyswgy.html