我如何为10,20,34和1的所有4个id执行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 :(得分: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)
答案 1 :(得分:0)
您可能忘记将x转换为str
{{1}}