请教,python web.py查询数据库返回的结果是列表还是字典
1个回答
展开全部
我常用pymssql连接M$SQL服务器, 没用过pyodbc, 但按理应该都差不多。
若用pymssql, 从数据库中取数据的过程如下:
import pymssql
connect_setting = {
'host': '127.0.0.1',
'user': 'sa',
'password': '',
'database': 'master',
'charset': 'gb18030'
}
conn = pymssql.connect(**connect_setting)
curr = conn.cursor()
curr.execute("select list, name from nlist")
result = [(lst, name) for lst, name in curr]
curr.close()
conn.close()
关于"如何查询,list的每个值在数据库中对应的Name“
若库表中的数据像下面的样子:
id, name:
1, 'python'
2, 'perl'
3, 'c'
4, 'java'
且每行id是唯一值, 将从数据库表中拿到的数据放到一个字典中:
curr.execute("select id, name from nlist")
dd = dict([(id, name) for id, name in curr])
lst = [1,2,3,4,5,6]
用dd进行转换
[(i, dd.get(i)) for i in lst]
==>
[(1, 'python'), (2, 'perl'), (3, 'c'), (4, 'java'), (5, None), (6, None)]
or
[dd.get(i, i) for i in lst]
==>
['python', 'perl', 'c', 'java', 5, 6]
若用pymssql, 从数据库中取数据的过程如下:
import pymssql
connect_setting = {
'host': '127.0.0.1',
'user': 'sa',
'password': '',
'database': 'master',
'charset': 'gb18030'
}
conn = pymssql.connect(**connect_setting)
curr = conn.cursor()
curr.execute("select list, name from nlist")
result = [(lst, name) for lst, name in curr]
curr.close()
conn.close()
关于"如何查询,list的每个值在数据库中对应的Name“
若库表中的数据像下面的样子:
id, name:
1, 'python'
2, 'perl'
3, 'c'
4, 'java'
且每行id是唯一值, 将从数据库表中拿到的数据放到一个字典中:
curr.execute("select id, name from nlist")
dd = dict([(id, name) for id, name in curr])
lst = [1,2,3,4,5,6]
用dd进行转换
[(i, dd.get(i)) for i in lst]
==>
[(1, 'python'), (2, 'perl'), (3, 'c'), (4, 'java'), (5, None), (6, None)]
or
[dd.get(i, i) for i in lst]
==>
['python', 'perl', 'c', 'java', 5, 6]
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询