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 ""
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 ""
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 ""
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()

本文链接:http://www.cnblogs.com/xuchunlin/p/6676300.html

上一篇:VxWorks:添加自己组件到Tornado


下一篇:安装Elasticsearch中Head插件并使用