2012-04-17 69 views
28

有沒有辦法在Python中使用列名而不是列索引檢索SQL結果列值?我用mySQL使用Python 3。我在尋找的語法是非常像Java結構:如何在Python中使用列名檢索SQL結果列值?

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

我有一個表,相當數量的列,它是一個真正的痛苦不斷制定出每列,我需要索引訪問。此外,索引使我的代碼難以閱讀。

謝謝!

+0

你可能希望提供更多的細節,比如你正在嘗試的一些代碼,你正在使用的python包。 – Shekhar 2012-04-17 16:27:53

回答

52

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

+6

嘗試了這一點,它不工作 - 得到一個錯誤「TypeError:元組索引必須是整數,而不是str」 – Thomas 2012-04-17 16:54:00

+2

您是否正在使用'MySQLdb'模塊?你是否像這樣創建了遊標:'cursor = conn.cursor(MySQLdb.cursors.DictCursor)'? – 2012-04-17 16:57:21

+0

我的不好!我沒有按照你的帖子創建光標。它現在可以工作 - 我只需要將MySQLdb.cursors.DictCursor更改爲pymysql.cursors.DictCursor,因爲我使用了pymysql。謝謝! – Thomas 2012-04-17 17:07:21

-1

當然有。在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 
+1

-1。對不起,嚴重懷疑這是OP的意思。 – 2012-04-17 16:30:59

+0

你認爲他想要做什麼?按列名選擇值並將它們分配給變量看起來非常簡單。 – TaoJoannes 2012-04-17 16:39:07

+0

看起來他想要一個獨立於列順序的解決方案。 – 2012-04-17 16:53:28

0

您沒有提供很多細節,但你可以嘗試這樣的事:

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

對不起,它不起作用。雖然我不確定是因爲mySQL實現還是DB-API-2.0缺乏支持。 – Thomas 2012-04-17 16:51:21

+0

您是否嘗試過使用pyodbc?它應該是通用的,併爲每個數據庫支持相同的接口。 – Diego 2012-04-17 18:25:24

-1

蟒蛇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] 
+0

OP要按屬性不索引 – levi 2017-05-15 17:20:15

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

進口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()