【问题标题】:Python, MySQL and SELECT output to dictionary with column names for keysPython、MySQL 和 SELECT 输出到带有键的列名的字典
【发布时间】:2011-09-01 09:04:41
【问题描述】:

我有一个 MySQL 表,我在 Python 中执行 SELECT 语句。

Python MySQLdb API 中是否有任何东西可以通过游标输出一个字典数组,其键是列名(值是返回行中的值)?

【问题讨论】:

  • 我猜是这个的副本:stackoverflow.com/questions/2180226/…
  • 也许你需要字典游标?cursor = conn.cursor (MySQLdb.cursors.DictCursor)
  • 如果你愿意,请将此链接设为我会接受的答案。
  • 如果您没有足够的声望投票关闭,请标记答案,选择“其他”,然后输入“重复”和 URL。 不要发布只是重复链接的答案。

标签: python mysql dictionary


【解决方案1】:

请使用字典光标:

cursor = conn.cursor (MySQLdb.cursors.DictCursor)

【讨论】:

    【解决方案2】:

    对我来说,this 工作:

    cursor = conn.cursor(dictionary=True)
    

    详细示例:

    import mysql.connector # pip install mysql-connector-python
    
    mydb = mysql.connector.connect(host="localhost", user="user", passwd="pass", database="dbname")
    cursor = conn.cursor(dictionary=True)
    sql = "SELECT * FROM `table` WHERE 1"
    mycursor.execute(sql)
    rows = mycursor.fetchall()
    for row in rows:
        row["col"]
    

    【讨论】:

    • 它正在使用 mysql.connector 库。
    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2023-03-09
    • 2019-06-13
    • 1970-01-01
    • 2020-01-24
    相关资源
    最近更新 更多