【问题标题】:SQL database query - return records which have all values from a list (Python)SQL 数据库查询 - 返回具有列表中所有值的记录(Python)
【发布时间】:2018-07-26 20:06:15
【问题描述】:

我已经设法从列表中查询并获取值的结果。但是假设我在用来查询的列表中有流派["Action", "Comedy", "Romance"]。我下面的代码返回动作、浪漫和喜剧的所有记录,而我希望它只返回满足所有三种类型的记录。我该怎么做?

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

代码:

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()

输出:

数据库:

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

【问题讨论】:

  • self.genreResults 是一个使用用户输入填充的列表,但根据用户选择的内容看起来像这样 ['Action', 'genrex']
  • 例如,如果你想查询包括Action&Comedy的记录,这个查询是否满足你的要求[select * from t wheregenre like '%Action%'和genre like '%Comedy%'] ?
  • 首先,感谢您的回答。但是我不能手动说出我想在 sql 语句中查询什么类型,因为我不知道用户会选择什么,因此我必须使用一个列表。我将如何为列表中的值执行这样的 sql 语句?

标签: python sql tkinter sqlite


【解决方案1】:

如果我理解正确,“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()

您可以参考mapstring join上的文档。

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

【讨论】:

  • 天啊,感谢我一直在互联网上搜索来解决这个问题。另外,感谢您提供链接,我了解您现在是如何解决的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多