【问题标题】:SQL Count error from within Python script. What am I doing wrong?Python 脚本中的 SQL 计数错误。我究竟做错了什么?
【发布时间】:2021-04-13 13:24:48
【问题描述】:

这是我正在运行的 SQL 命令。我不断返回的结果是 None,但我确信至少有 1300 条记录符合这些条件。有什么想法吗?

count_unchecked = "SELECT COUNT(website_url) FROM url_list WHERE http_response=200 AND is_website IS NULL"
number_unchecked = mycursor.execute(count_unchecked)
mydb.close()
    print("This program will attempt to identify which of the URLs collected are camped.")
    print("Currently, there are", number_unchecked, "records that have not been checked.")
    urls_to_check = input("How many URLs would you like to check?")

我选择计算 website_url 列是因为每条记录都填充了该列。任何想法为什么它返回 None

最终解决方案: 这是最终解决方案的代码!我了解到 fetchone 返回一个元组,所以为了让它看起来尽可能干净,我必须引用元组中的第一个元素。

mycursor = mydb.cursor()

count_unchecked = "SELECT COUNT(website_url) FROM url_list WHERE http_response=200 AND is_website IS NULL"
mycursor.execute(count_unchecked)
fetched = mycursor.fetchone()
number_unchecked = fetched[0]
mydb.close()

【问题讨论】:

  • 也许条件is_website应该是is not null
  • 您在寻找没有网站的 URL 吗?根据您的数据库,您可能还需要引用 200
  • 此脚本的其余部分将填充 is_website 字段。所以这部分会告诉用户需要检查多少个 URL 以查看它们是否只是被抢注。实际上,我所做的只是计算有多少记录在 is_website 字段中没有任何内容,默认情况下设置为 NULL。
  • 删除了 http_response 条件以检查是否是问题所在。仅使用 is_website IS NULL 条件会产生相同的结果。
  • 哇。即使去掉所有条件也不会产生任何结果。

标签: python mysql sql select count


【解决方案1】:

问题是您必须获取结果,因为默认情况下cursor.execute 返回None

mycursor.execute(count_unchecked)
row = mycursor.fetchone()
number_unchecked = row[0]

请参阅relevant documentation

【讨论】:

    猜你喜欢
    • 2016-07-18
    • 2014-06-15
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    相关资源
    最近更新 更多