python 执行sql得到字典格式数据
本文在提供一种方式,实现执行sql语句 返回字典结果集
# 连接数据库,数据库的,这里使用的setting中的默认设置,在这里不做具体的介绍,不懂的可以百度一下 conn = MySQLdb.connect(host=settings.DATABASES['default']['HOST'], user=settings.DATABASES['default']['USER'], passwd=settings.DATABASES['default']['PASSWORD'], db=settings.DATABASES['default']['NAME']) cursor = conn.cursor() # 原生sql语句,注意要用六个 " sql = """ SELECT total_premium,quote_count,order_count from usr_statistics WHERE DAY = 20170422""" # 执行sql cursor.execute(sql) # 只用于select语句,返回一行的列名 desc = cursor.description print "00000000000000000" print desc # desc 将会输出 (('total_premium', 246, 7, 26, 26, 2, 0), ('quote_count', 3, 3, 11, 11, 0, 0), ('order_count', 3, 3, 11, 11, 0, 0)) object_dict = [ dict(zip([col[0] for col in desc],row)) for row in cursor.fetchall() ] cursor.close() print "1111111111111111111" print object_dict # 下面是object_dict的输出,太长了,已经给其换行 # [{'quote_count': 5L, 'total_premium': Decimal('200.00'), 'order_count': 7L}, # {'quote_count': 5L, 'total_premium': Decimal('200.00'), 'order_count': 7L}, # {'quote_count': 45L, 'total_premium': Decimal('999.00'), 'order_count': 78L}, # {'quote_count': 65L, 'total_premium': Decimal('999.00'), 'order_count': 78L}, # {'quote_count': 45L, 'total_premium': Decimal('888.00'), 'order_count': 78L}, # {'quote_count': 123L, 'total_premium': Decimal('523.00'), 'order_count': 23L}, # {'quote_count': 2L, 'total_premium': Decimal('211.00'), 'order_count': 21L}, # {'quote_count': 1L, 'total_premium': Decimal('0.00'), 'order_count': 23L}, # {'quote_count': 23L, 'total_premium': Decimal('213.00'), 'order_count': 23L}, # {'quote_count': 13L, 'total_premium': Decimal('1232.00'), 'order_count': 123L}, # {'quote_count': 0L, 'total_premium': Decimal('0.00'), 'order_count': 1L}, # {'quote_count': 0L, 'total_premium': Decimal('0.00'), 'order_count': 0L}, # {'quote_count': 0L, 'total_premium': Decimal('0.00'), 'order_count': 0L}, # {'quote_count': 0L, 'total_premium': Decimal('0.00'), 'order_count': 0L}, # {'quote_count': 0L, 'total_premium': Decimal('0.00'), 'order_count': 0L}] object_list = [] object_list_b = [] for i in object_dict: object_list.append(int(i.get("total_premium"))) object_list_b.append(i.get("quote_count")) print "22222222222222222222" print object_list print object_list_b # object_list输出 [200, 200, 999, 999, 888, 523, 211, 0, 213, 1232, 0, 0, 0, 0, 0] # object_list_b输出 [5L, 5L, 45L, 65L, 45L, 123L, 2L, 1L, 23L, 13L, 0L, 0L, 0L, 0L, 0L] conn.close()
如果觉得对您有帮助,麻烦您点一下推荐,谢谢!
好记忆不如烂笔头
好记忆不如烂笔头
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术