0

我有这个代码。

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 列的查询中。我试过这个,但它对我不起作用

谢谢!

4

2 回答 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)

更新

更新了代码以选择行名。我猜不是万无一失的。测试一下:)

于 2013-03-24T22:00:58.007 回答
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']])
于 2013-03-24T22:44:23.543 回答