2013-03-24 18 views
0

我有这段代码。从sql查询输出创建一个列表,使用属性名称而不是索引使用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列输出的查询中。 我试过this但它不适用于我

谢谢!

回答

1

35分钟后reshearch的,我发现这个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']]) 
+1

很酷;那个显示所有行属性:)。我刚刚找到'cursor.column_names',它实际上只是返回行名('cursor.description [n]')。很好的例子! – 2013-03-24 22:48:29

+0

谢谢Allendar! :) – mongotop 2013-03-24 23:45:53

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) 

更新

更新的代码来选择行的名称了。我猜不是万无一失的。测试它的一些:)

+0

这完美的作品,如果我们有1个输出!如果我们有一个sql查询有2个输出,那么怎么样?非常感谢Allendar !!!! – mongotop 2013-03-24 22:05:18

+1

我已经更新了答案。它获得所有输出。如果您仍然得到一行,则比您在查询中使用LIMIT或读取输出错误。如果你把这个代码干净地粘贴到一个新文件中(没有任何干扰),它应该可以工作。将'clients_db'更改为您的数据库名称。 – 2013-03-24 22:11:34

+0

是的,它的工作原理!也许我的问题是如何将索引“0”更改为“id”引用与列名称的索引。 – mongotop 2013-03-24 22:15:43

相关问题