使用python从sql查询输出创建一个具有属性名而不是索引的列表
我有这个密码使用python从sql查询输出创建一个具有属性名而不是索引的列表,python,mysql,list,tuples,Python,Mysql,List,Tuples,我有这个密码 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'])
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”对象不可调用
你知道为什么这不可能吗?有没有其他方法可以做到这一点,因为在一个输出超过20列的查询中,当我把属性名放在索引中时,它更全面。 我试过了,但不管用 谢谢 试试这个:
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分钟的重听后,我发现: 解决方案是添加这一行,使用
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']])
如果我们有1个输出,这将非常有效!如果一个sql查询有两个输出,怎么样?非常感谢Allendar!!!!我已经更新了答案。它得到所有的输出。如果仍然得到一行,则表示对查询使用了限制或读取输出错误。如果您将此代码粘贴到一个新文件中(没有任何干扰),它应该可以工作。将
clients\u db
更改为您的数据库名称。是的,它可以工作!!也许我的问题是如何将索引“0”更改为对具有列名的索引的“id”引用。我已再次更新了答案。它现在也应该选择行名了;该行显示所有行属性:)。我刚刚找到了cursor.column\u names
,它实际上只是返回行名(cursor.description[n]
)。很好的例子!