Hoe de waarde van de SQL-resultaatkolom op te halen met behulp van de kolomnaam in Python?

Is er een manier om de kolomwaarde van het SQL-resultaat op te halen met behulp van de kolomnaam in plaats van de kolomindex in Python? Ik gebruik Python 3 met mySQL. De syntaxis die ik zoek lijkt veel op de Java-constructie:

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

Ik heb een tabel met een behoorlijk aantal kolommen en het is een hele klus om constant de index uit te werken voor elke kolom die ik nodig heb. Bovendien maakt de index mijn code moeilijk leesbaar.

Bedankt!


Antwoord 1, autoriteit 100%

De MySQLdb-module heeft een DictCursor:

Gebruik het als volgt (overgenomen van MySQL-scripts schrijven met 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"])

edit:Volgens user1305650 werkt dit ook voor pymysql.


Antwoord 2, autoriteit 29%

Dit bericht is oud, maar kan via zoeken naar voren komen.

Nu kunt u mysql.connector gebruiken om een ​​woordenboek op te halen, zoals hier wordt weergegeven:
https://dev.mysql.com/doc /connector-python/en/connector-python-api-mysqlcursordict.html

Hier is het voorbeeld op de mysql-site:

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

Antwoord 3, autoriteit 19%

je moet zoeken naar iets genaamd ” woordenboek in cursor “

ik gebruik de mysql-connector en ik moet deze parameter aan mijn cursor toevoegen, zodat ik mijn kolomnamen kan gebruiken in plaats van index’s

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)

Antwoord 4, autoriteit 14%

pymysql importeren

# 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()

Antwoord 5, autoriteit 6%

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]

Antwoord 6, autoriteit 5%

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': '[email protected]'}
print(result["Id"])
# output => 1
print(result["Email"])
# output => [email protected]

Antwoord 7, autoriteit 3%

Natuurlijk is dat zo. In 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

Antwoord 8, autoriteit 2%

waarden selecteren uit een bepaalde kolom:

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)

Antwoord 9

Je hebt niet veel details gegeven, maar je zou zoiets als dit kunnen proberen:

# 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()

Antwoord 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 ]

Other episodes