【问题标题】:creat a list from sql query output with the attribute name instead of the index using python使用属性名称而不是使用 python 的索引从 sql 查询输出创建列表
【发布时间】:2013-03-24 21:36:00
【问题描述】:

我有这个代码。

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 但它对我不起作用

谢谢!

【问题讨论】:

    标签: python mysql list tuples


    【解决方案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']])
    

    【讨论】:

    • 酷;那一个显示所有行属性:)。我刚刚找到cursor.column_names,它实际上只是返回行名(cursor.description[n])。很好的例子!
    【解决方案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)
    

    更新

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

    【讨论】:

    • 如果我们有 1 个输出,这很完美!如果我们有来自 sql 查询的 2 个输出呢?非常感谢艾伦达!!!!
    • 我已经更新了答案。它得到所有输出。如果您仍然得到一行,则说明您在查询中使用了 LIMIT 或错误地读取了输出。如果您将此代码干净地粘贴到新文件中(没有任何干扰),它应该可以工作。将 clients_db 更改为您的数据库名称。
    • 是的,它有效!也许我的问题是如何将索引“0”更改为“id”对具有列名的索引的引用。
    • 我再次更新了答案。它现在也应该选择行名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多