我有这段代码。
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列输出的查询中。
我试过this,但它对我不起作用
谢谢!
答案 0 :(得分: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 :(得分:1)
经过35分钟的重新整理后,我发现了post:
解决方案是添加此行以使用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']])