gpt4 book ai didi

python - SQL 数据库查询 - 返回包含列表中所有值的记录 (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:53 25 4
gpt4 key购买 nike

我已成功查询并获取列表中的值的结果。但是假设我在用于查询的列表中有类型 ["Action", "Comedy", "Romance"] 。我下面的代码返回 Action 、浪漫和喜剧的所有记录,而我希望它只返回满足所有三种类型的记录。我怎样才能做到这一点?

数据库有一个称为流派的字段,其中每条记录有多个流派。

代码:

with sqlite3.connect("animeData.db") as  db: #anime database
c = db.cursor()
c.execute("select * from t where genre in %s" % repr(self.genreResults).replace('[','(').replace(']',')') ) #self.genreResults is the list containing the genres i want to query
results = c.fetchall()
print(results)
db.commit()
db.close()

输出:

数据库:

它返回所有具有 Action 和冒险类型的动漫,而我只希望它返回同时具有这两种类型的动漫。有什么建议么?

最佳答案

如果我理解正确的话,“like”子句满足您的要求,但您不知道如何将列表转换为“like”子句。

所以代码如下:

import sqlite3

with sqlite3.connect("animeData.db") as db: #anime database
c = db.cursor()
#self.genreResults is the list containing the genres i want to query
user_input = self.genreResults # for example: ['Action','Drama']
convert_to_like_conditions = ' and '.join(list(map(lambda item : "genre like '%{0}%'".format(item), user_input)))
print(convert_to_like_conditions) #Output: genre like '%Action%' and genre like '%Drama%'
c.execute("select * from t where %s" % convert_to_like_conditions )
results = c.fetchall()
print(results)
db.commit()

可以引用map上的文档, string join .

你可能注意到我删除了你代码的最后一行(db.close),你可以引用Understanding Python's "with" statement .

关于python - SQL 数据库查询 - 返回包含列表中所有值的记录 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48817876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com