按照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)
你目前收到了什麼結果?期望的結果如何不同? –
獲取錯誤 - TypeError:'int'對象不可迭代。不知道我出錯的地方 –
堆棧跟蹤會告訴你發生錯誤的線路。在這種情況下,哪條線? –