如何使用Python中的列名检索SQL结果列值?

Tho*_*mas 45 python mysql

有没有办法在Python中使用列名而不是列索引来检索SQL结果列值?我正在使用Python 3和mySQL.我正在寻找的语法非常类似于Java构造:

Object id = rs.get("CUSTOMER_ID"); 
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Ste*_*ski 80

MySQLdb的模块具有DictCursor:

像这样使用它(取自使用Python DB-API编写MySQL脚本):

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"])
Run Code Online (Sandbox Code Playgroud)

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

  • 试过这个并且它也不起作用 - 得到一个错误"TypeError:元组索引必须是整数,而不是str" (7认同)
  • 你在使用`MySQLdb`模块吗?你是否完全像这样创建了光标:`cursor = conn.cursor(MySQLdb.cursors.DictCursor)`? (3认同)
  • 它实际上比这简单得多,你不需要任何不同的模块:/sf/answers/3934691211/ (2认同)

小智 15

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

我正在使用 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)
Run Code Online (Sandbox Code Playgroud)


voa*_*oam 13

这篇文章很老,但可能会通过搜索找到.

现在您可以使用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']
Run Code Online (Sandbox Code Playgroud)


小智 10

导入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()
Run Code Online (Sandbox Code Playgroud)


Irf*_*raf 7

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
Run Code Online (Sandbox Code Playgroud)


小智 5

蟒蛇 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]
Run Code Online (Sandbox Code Playgroud)