我常用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]
追问我现在已经将数据库中的数据拿到了一个二维矩阵中,用numpy的array做的。。怎么转成字典。。。
追答>>> import numpy as np
>>>
>>> aresult = np.array([[1,23], [2,53], [3,64], [4,78], [5,26], [6, 98]])
>>> aresult
array([[ 1, 23],
[ 2, 53],
[ 3, 64],
[ 4, 78],
[ 5, 26],
[ 6, 98]])
>>> dict(aresult)
{1: 23, 2: 53, 3: 64, 4: 78, 5: 26, 6: 98}
>>>
追问怎么样 查询是None的值不显示出来哇?
追答>>> aresult = np.array([[1,23], [2,53], [3,64], [4,78], [5,None], [6,None]])
>>> aresult[aresult[:,1]>=0]
array([[1, 23],
[2, 53],
[3, 64],
[4, 78]], dtype=object)
>>>
来自:求助得到的回答