【问题标题】:How to retrieve SQL result column value using column name in Python?如何在 Python 中使用列名检索 SQL 结果列值?
【发布时间】:2012-04-17 16:23:43
【问题描述】:

有没有办法在 Python 中使用列名而不是列索引来检索 SQL 结果列值?我将 Python 3 与 mySQL 一起使用。我正在寻找的语法很像 Java 构造:

Object id = rs.get("CUSTOMER_ID"); 

我有一个包含相当多列的表,不断地为我需要访问的每一列计算索引真的很痛苦。此外,索引使我的代码难以阅读。

谢谢!

【问题讨论】:

  • 你可能想提供更多细节,比如你正在尝试的一些代码,你正在使用的 python 包。
  • 有关cursor.description的更多信息,请参阅cursor.description

标签: python mysql


【解决方案1】:

MySQLdb 模块有一个DictCursor

这样使用(取自Writing MySQL Scripts with Python DB-API):

cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT name, category FROM animal")
result_set = cursor.fetchall()
for row in result_set:
    print "%s, %s" % (row["name"], row["category"])

编辑:根据 user1305650,这也适用于 pymysql

【讨论】:

  • 试过了,它也不起作用 - 收到错误“TypeError: tuple indices must be integers, not str”
  • 您在使用MySQLdb 模块吗?您是否完全像这样创建光标:cursor = conn.cursor(MySQLdb.cursors.DictCursor)
  • 我的错!我没有根据您的帖子创建光标。它现在可以工作了——我只需要将 MySQLdb.cursors.DictCursor 更改为 pymysql.cursors.DictCursor,因为我使用 pymysql。谢谢!
  • 优秀。您可以通过按左侧的复选标记来接受此答案。如果你真的喜欢它,你也可以添加一个upvote。 :)
  • 它实际上比这简单得多,你不需要任何不同的模块:stackoverflow.com/a/56209874/1164342
【解决方案2】:

这篇文章很旧,但可以通过搜索找到。

现在您可以使用 mysql.connector 检索字典,如下所示: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

这是mysql网站上的例子:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']))

【讨论】:

  • 此注释在代码示例末尾缺少两个右括号,例如print("* {Name}".format(Name=row['Name'].
  • 这是 >2020 和 Python >3 的最佳答案。这对我帮助很大!不需要orderedDicts等。
【解决方案3】:

你必须寻找一个叫做“光标中的字典”的东西

我正在使用 mysql 连接器,我必须将此参数添加到我的光标,所以我可以使用我的列名而不是索引的

db = mysql.connector.connect(
    host=db_info['mysql_host'],
    user=db_info['mysql_user'],
    passwd=db_info['mysql_password'],
    database=db_info['mysql_db'])

cur = db.cursor()

cur = db.cursor( buffered=True , dictionary=True)

【讨论】:

  • 这是正确的答案。
【解决方案4】:

导入 pymysql

# Open database connection
db = pymysql.connect("localhost","root","","gkdemo1")

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT * from user")

# Get the fields name (only once!)
field_name = [field[0] for field in cursor.description]

# Fetch a single row using fetchone() method.
values = cursor.fetchone()

# create the row dictionary to be able to call row['login']
**row = dict(zip(field_name, values))**

# print the dictionary
print(row)

# print specific field
print(**row['login']**)

# print all field
for key in row:
    print(**key," = ",row[key]**)

# close database connection
db.close()

【讨论】:

    【解决方案5】:

    python 2.7

    import pymysql
    
    conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')
    
    cur = conn.cursor()
    
    n = cur.execute('select * from actor')
    c = cur.fetchall()
    
    for i in c:
        print i[1]
    

    【讨论】:

    • OP 想要按属性而不是索引
    【解决方案6】:
    import mysql
    import mysql.connector
    
    db = mysql.connector.connect(
       host = "localhost",
        user = "root",
        passwd = "P@ssword1",
        database = "appbase"
    )
    
    cursor = db.cursor(dictionary=True)
    
    sql = "select Id, Email from appuser limit 0,1"
    cursor.execute(sql)
    result = cursor.fetchone()
    
    print(result)
    # output =>  {'Id': 1, 'Email': 'me@gmail.com'}
    
    print(result["Id"])
    # output => 1
    
    print(result["Email"])
    # output => me@gmail.com
    

    【讨论】:

      【解决方案7】:

      当然有。在 Python 2.7.2+...

      import MySQLdb as mdb
      con =  mdb.connect('localhost', 'user', 'password', 'db');
      cur = con.cursor()
      cur.execute('SELECT Foo, Bar FROM Table')
      for i in range(int(cur.numrows)):
          foo, bar = cur.fetchone()
          print 'foo = %s' % foo
          print 'bar = %s' % bar
      

      【讨论】:

      • 你认为他想做什么?按列名选择值并将它们分配给变量看起来很简单。
      • 看起来他想要一个独立于列顺序的解决方案。
      • 这也有效,但它只是在我的代码中增加了所有额外的变量。我认为 Steven Rumbalski 的上一篇文章是一个更好的解决方案。无论如何也感谢您的解决方案。
      【解决方案8】:

      从特定列中选择值:

      import pymysql
      db = pymysql.connect("localhost","root","root","school")
      cursor=db.cursor()
      sql="""select Total from student"""
      l=[]
      try:
          #query execution
          cursor.execute(sql)
          #fetch all rows 
          rs = cursor.fetchall()
          #iterate through rows
          for i in rs:
              #converting set to list
              k=list(i)
              #taking the first element from the list and append it to the list
              l.append(k[0])
          db.commit()
      except:
          db.rollback()
      db.close()
      print(l)
      

      【讨论】:

        【解决方案9】:

        你没有提供很多细节,但你可以试试这样:

        # conn is an ODBC connection to the DB
        dbCursor = conn.cursor()
        sql = ('select field1, field2 from table') 
        dbCursor = conn.cursor()
        dbCursor.execute(sql)
        for row in dbCursor:
            # Now you should be able to access the fields as properties of "row"
            myVar1 = row.field1
            myVar2 = row.field2
        conn.close()
        

        【讨论】:

        • 对不起,它不起作用。虽然我不确定是因为 mySQL 实现还是 DB-API-2.0 缺乏对它的支持。
        • 你试过使用pyodbc吗?它应该是通用的,并且支持每个数据库的相同接口。
        【解决方案10】:
        import mysql.connector as mysql
        ...
        cursor = mysql.cnx.cursor()
        cursor.execute('select max(id) max_id from ids')
        (id) = [ id for id in cursor ]
        

        【讨论】:

        • 或者更简洁的最后一行可以是 id = [ id for id in cursor ][0][0]
        • 欢迎来到 Stack Overflow。虽然此命令可能会回答问题,但提供有关此代码为何和/或如何回答问题的附加上下文会提高其长期价值。 How to Answer
        猜你喜欢
        • 2011-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-30
        相关资源
        最近更新 更多