2017-09-19 135 views
0

我如何執行SELECT語句對所有的4名ID的是10,20,34和1所期望的結果是在一個列表蟒蛇疊代SQL查詢select語句

import pymysql 
import json 

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', 
db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) 

cursor = conn.cursor() 

select_query = "select * from users where id = " 
ids = ["10", "20", "34", "1"] 
for x in ids: 
    var = select_query + x 
    # print(var) 
    print(list(cursor.execute(var))) 
+0

你目前收到了什麼結果?期望的結果如何不同? –

+0

獲取錯誤 - TypeError:'int'對象不可迭代。不知道我出錯的地方 –

+0

堆棧跟蹤會告訴你發生錯誤的線路。在這種情況下,哪條線? –

回答

1

按照PyMySQL docs,該cursor.execute()函數返回一個int,這就是爲什麼你的錯誤被顯示出來。你要調用,然後使用fetch functions的一個實際返回的結果

import pymysql 

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', 
         db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) 

cursor = conn.cursor() 

select_query = "select * from users where id = " 
ids = ["10", "20", "34", "1"] 
for x in ids: 
    var = select_query + x 
    # print(var) 
    cursor.execute(var) 
    print(list(cursor.fetchall())) 

或者,如果你希望所有的結果在一個列表中:

import pymysql 

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', 
         db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) 

cursor = conn.cursor() 

lst = [] 

select_query = "select * from users where id = " 
ids = ["10", "20", "34", "1"] 
for x in ids: 
    var = select_query + x 
    # print(var) 
    cursor.execute(var) 
    lst.extend(cursor.fetchall()) 

print(lst) 

或字典

import pymysql 

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', 
         db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) 

cursor = conn.cursor() 

results = {} 

select_query = "select * from users where id = " 
ids = ["10", "20", "34", "1"] 
for x in ids: 
    var = select_query + x 
    # print(var) 
    cursor.execute(var) 
    results[x] = list(cursor.fetchall()) 

print(results) 
+0

謝謝:)工作得很好 –

0

你可能忘了強制轉換X爲str

import pymysql 
import json 

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', 
db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) 

cursor = conn.cursor() 

select_query = "select * from users where id = " 
ids = ["10", "20", "34", "1"] 
for x in ids: 
    var = select_query + str(x) # here 
    # print(var) 
    print(list(cursor.execute(var))) 
+0

得到相同的錯誤 - 堆棧跟蹤。 回溯(最近一次調用最後一次): 打印(list(cursor.execute(var)) 文件「C:\ xampp \ htdocs \ sandbox \ for.py」,第14行, TypeError:'int'對象不可迭代 –