Как получить значение столбца результата SQL с использованием имени столбца в Python?
Есть ли способ получить значение столбца результата SQL, используя имя столбца вместо индекса столбца в Python? Я использую Python 3 с mySQL. Синтаксис, который я ищу, во многом похож на конструкцию Java:
Object id = rs.get("CUSTOMER_ID");
У меня есть таблица с довольно большим количеством столбцов, и это настоящая боль, чтобы постоянно разрабатывать индекс для каждого столбца, который мне нужен. Кроме того, индекс делает мой код трудным для чтения.
Спасибо!
Ответы
Ответ 1
Модуль MySQLdb имеет DictCursor:
Использовать его так (взято из Написание скриптов MySQL с помощью 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: В соответствии с user1305650 это работает для pymysql
.
Ответ 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']
Ответ 3
import 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()
Ответ 4
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]
Ответ 5
Конечно, есть. В 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
Ответ 6
Вы не указали много деталей, но можете попробовать что-то вроде этого:
# 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()
Ответ 7
выбор значений из определенного столбца:
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)
Ответ 8
import mysql.connector as mysql
...
cursor = mysql.cnx.cursor()
cursor.execute('select max(id) max_id from ids')
(id) = [ id for id in cursor ]
Ответ 9
вы должны искать то, что называется "словарь в курсоре"
я использую соединитель 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)