使用python从sql查询输出创建一个具有属性名而不是索引的列表

2024-05-18 19:13:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码。在

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列的查询中时,它比索引更全面。 我试过了,但没用

谢谢!在


Tags: namefromclientid密码executethatselect
2条回答

试试这个:

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)

更新

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

35分钟后,我发现了这个post: 解决方案是添加这一行,使用description内置函数将索引更改为列名。在

name_to_index = dict( (d[0], i) for i, d in enumerate(cursor.description) )

之后我要做的就是调用这个新函数,比如:

^{pr2}$

相关问题 更多 >

    热门问题