2015-02-09 20 views
1

我有一個mysql數據庫,我通過MAMP管理(使用端口3306,服務器在端口80上)。我已經從Oracle下載並安裝了mysql-connector-python庫,並試圖訪問和操作數據庫。奇怪的是,按照http://dev.mysql.com/doc/connector-python/en/connector-python-tutorial-cursorbuffered.html的教程,我可以運行查詢將新記錄插入到特定的表中(只要我在連接器上發出.commit()方法)。從mysql中選擇數據與mysql-connector-python

但是,我似乎無法用簡單的選擇命令來檢索任何數據。所以查詢「Select * from Assignments」返回None。

query = ('''SELECT title,description FROM `Assignments` LIMIT 0 , 30''') 

cursor = cnx.cursor() 
result = cursor.execute(query) 
print "result:",result 

#All assignment info 
for (title, description) in results: 
    print title, description 

我不斷收到錯誤,「TypeError:'NoneType'對象不可迭代」。我認爲這與執行查詢的結果是None無關。 B/c我可以提交更新並將更改插入到數據庫,我知道我連接的很好。爲什麼我不能運行簡單的SELECT命令並獲取某些內容?

回答

2

您應該使用MySQLCursor.fetchall方法來獲得結果。

cursor.execute(query) 
rows = cursor.fetchall() 

cursor.execute(query) 
head_rows = cursor.fetchmany(size=2) 
remaining_rows = cursor.fetchall() 
+0

謝謝@亞歷山大!這工作很好。我想知道爲什麼它沒有在文檔教程頁面(http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html)中提到。什麼是錯誤的結果(對我而言)。 – staypuffinpc 2015-02-09 19:27:22

0

你不需要調用使用fetchall,如果你看看你會看到文檔沒有分配到執行調用的方法的返回值返回,你只是執行然後遍歷MySQLCursor/cursor對象:

query = ('''SELECT title,description FROM `Assignments` LIMIT 0 , 30''') 

cursor = cnx.cursor() 

# forget assigning, just execute 
cursor.execute(query) 

# iterate over the cursor 
for (title, description) in cursor: 
    print title, description