56

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

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

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

谢谢!

4

10 回答 10

93

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"])

编辑:根据 user1305650 这也适用pymysql

于 2012-04-17T16:38:38.013 回答
29

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

现在您可以使用 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']))
于 2017-11-14T21:59:27.960 回答
18

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

我正在使用 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)
于 2019-05-19T16:35:36.973 回答
13

导入 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()
于 2017-12-23T19:06:24.583 回答
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
于 2019-08-02T12:31:44.133 回答
6

蟒蛇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]
于 2017-05-05T12:17:16.333 回答
3

当然有。在 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
于 2012-04-17T16:29:12.570 回答
2

从特定列中选择值:

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)
于 2019-01-09T07:04:51.723 回答
1

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

# 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()
于 2012-04-17T16:31:22.757 回答
0
import mysql.connector as mysql
...
cursor = mysql.cnx.cursor()
cursor.execute('select max(id) max_id from ids')
(id) = [ id for id in cursor ]
于 2019-03-25T20:53:55.960 回答