简体   繁体   English

遍历列表 Python SQL

[英]Iterating through a list Python SQL

I'm trying to search a database, by iterating through a list of search values.我正在尝试通过遍历搜索值列表来搜索数据库。 I'm almost there as this works for integers but not strings.我快到了,因为这适用于整数,但不适用于字符串。 The code below won't work, but if I replace the list values with numbers it does:下面的代码不起作用,但如果我用数字替换列表值,它会:

mycursor = mydb.cursor()

lst = []

select_query = "SELECT * FROM fruit WHERE content LIKE "
ids = ["apple", "pear"]

for x in ids:
    var = select_query + str(x)
    
    mycursor.execute(var)
    lst.extend(mycursor.fetchall())

print(lst)

It's because you have to enclose strings in quotation marks in SQL.这是因为您必须在 SQL 中将字符串括在引号中。 So for example所以例如

SELECT * FROM fruit WHERE content LIKE 'pears'

will work, and it will only work with the single quotations around "pears".将起作用,并且仅适用于“梨”周围的单引号。 Even better, type conversion can (and should) be done automatically with psycopg2:更好的是,类型转换可以(并且应该)使用 psycopg2 自动完成:

select_query = "SELECT * FROM fruit WHERE content LIKE %s"
...
mycursor.execute(select_query, (x,))

https://www.psycopg.org/docs/usage.html#strings-adaptation https://www.psycopg.org/docs/usage.html#strings-adaptation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM