用Python从SQL查询输出创建带属性名的列表而非索引
我有这段代码。
cursor.execute("select id, name from client")
clientids= cursor.fetchall()
clientidList = []
for clientid in clientids:
#I can do that
clientidList.append(clientid [0])
#but I can't do that.
clientidList.append(clientid ['id'])
在第二次尝试时,我遇到了一个错误:TypeError: 'tuple' object is not callable
你知道为什么会出现这个问题吗?有没有其他方法可以做到这一点?因为在查询输出超过20列的时候,使用属性名称比用索引更容易理解。我试过这个方法,但对我来说不管用。
谢谢!
2 个回答
1
试试这个:
import mysql.connector
db_config = {
'user': 'root',
'password': 'root',
'port' : '8889',
'host': '127.0.0.1',
'database': 'clients_db'
}
cnx = {} # Connection placeholder
cnx = mysql.connector.connect(**db_config)
cur = cnx.cursor()
cur.execute('SELECT id FROM client')
columns = cur.column_names
clientids = []
for (entry) in cur:
count = 0
buffer = {}
for row in entry:
buffer[columns[count]] = row
count += 1
clientids.append(buffer)
cur.close()
clientidList = []
for client in clientids:
clientidList.append(client['id'])
pprint.pprint(clientids)
pprint.pprint(clientidList)
更新
我更新了代码,现在也可以选择行名称了。不过我觉得这不是百分之百可靠的。你可以试试看 :)
1
经过35分钟的研究,我找到了一篇帖子:这里。解决办法是添加这一行代码,用来通过description
这个内置函数把索引改成列名。
name_to_index = dict( (d[0], i) for i, d in enumerate(cursor.description) )
接下来我只需要像这样调用这个新函数:
clientidList = []
for clientid in clientids:
clientidList.append(clientid[name_to_index['id']])