C/C++教程

如何对Sqlalchemy的查询结果进行解析

本文主要是介绍如何对Sqlalchemy的查询结果进行解析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Sqlalchemy的查询方式

  • 查询全部:
    类型为列表,返回值为对象,可以使用索引,res[2]
  • 查询指定条件:
    类型是个对象,返回值是个sql语句,不可以使用索引
  • 查询指定字段:
    类型是个对象,返回值是个sql语句

 

Sqlalchemy的查询结果类型及返回值都有哪些区别?

  • 查询全部,查询实体类里面的所有数据,也就是查询UplineRecord表的所有数据,返回的类型是列表里面嵌套对象
  • def query():
        # 查询全部------查询实体类里面的所有数据,也就是查询UplineRecord表的所有数据
         --------------类型为列表,返回值为对象(返回的是实体类里的对象,即数据库里的数据,)
        res = session.query(UplineRecord).all()
        print("类型", type(res))
        print("返回值:", res)
    if __name__ == '__main__':
        print(query())
    
    #打印结果
    类型 <class 'list'>
    返回值: [<entity.Associated_database.UplineRecord object at 0x00000171A1AC5120>]
    
    def query(id):
        # 查询指定条件,类型是个对象,返回值是个sql语句
        res = session.query(UplineRecord).filter(UplineRecord.id == id)
        print("类型", type(res))
        print("返回值:", res)
    if __name__ == '__main__':
        print(query(50))
    #打印结果
    类型 <class 'sqlalchemy.orm.query.Query'>
    返回值: SELECT upline_record.id AS upline_record_id, upline_record.service_group AS upline_record_service_group, upline_record.application_name AS upline_record_application_name, upline_record.online_version AS upline_record_online_version, upline_record.work_order AS upline_record_work_order, upline_record.requirement AS upline_record_requirement, upline_record.developer AS upline_record_developer, upline_record.tester AS upline_record_tester, upline_record.test_report_id AS upline_record_test_report_id, upline_record.`sql` AS upline_record_sql, upline_record.apollo AS upline_record_apollo, upline_record.emergency_online AS upline_record_emergency_online, upline_record.`status` AS upline_record_status, upline_record.`delete` AS upline_record_delete, upline_record.online_time AS upline_record_online_time, upline_record.create_time AS upline_record_create_time, upline_record.update_time AS upline_record_update_time, upline_record.dingding_notification AS upline_record_dingding_notification
    FROM upline_record
    WHERE upline_record.id = %(id_1)s
    
    # 对查询结果进行数据解析
    def query():
        # 查询所有
        res = session.query(UplineRecord).all()
    
       #第一种解析方式,查询结果是list里面嵌套多个对象,可对对象进行循环处理,获取到的每个结果在丢入到列表中,在返回这个列表中的内容
        test_item = [item.to_dict() for item in res]
        return test_item
    
       #第二种解析方式
        list = []
        for i in res:
             list.append(i.to_dict())
         return list
    if __name__ == '__main__':
        print(query())

     

这篇关于如何对Sqlalchemy的查询结果进行解析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!