【问题标题】:No match found in mysql DB with python even though results are in the table即使结果在表中,也没有在 mysql DB 和 python 中找到匹配项
【发布时间】:2021-01-18 13:46:44
【问题描述】:

我有生成随机数的代码,以及一个 mysql 数据库,其中的一些数字应该与许多随机生成的数字相匹配。一旦找到匹配项,该程序应该会中断,但是即使我看到生成了几个匹配项,它也会继续运行。我多次检查数据库,所有数字都在那里。我是编码新手,所以我想我查询数据库错误?将不胜感激任何帮助。谢谢

import random
import mysql.connector

mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    passwd = "password",
    database = "testdb"
)


my_database = mydb.cursor()
sql_statement = "SELECT * FROM numbers"

my_database.execute(sql_statement)
output = my_database.fetchall()


while True:

    ran = random.randrange(100000,200000,100)

    if ran in output:
        print("MATCH!",ran)
        break
    else:
        print(ran)
'''


【问题讨论】:

  • fetchall() 返回一个元组列表。 ran 是一个整数,它不等于元组(即使元组包含整数作为其唯一项)。您需要遍历每个元组。
  • 感谢您的回复。您的意思是在第 16 行添加 'for x in output:' 然后缩进其余部分吗?
  • 或者,如果表格只有一列,你可以说if (ran,) in output:
  • 成功了!非常感谢!
  • 你做过调试吗?我建议阅读ericlippert.com/2014/03/05/how-to-debug-small-programs

标签: python mysql python-3.x mysql-workbench


【解决方案1】:

根据 mysql python 连接器文档,fetchall() 返回一个元组列表。因此,您需要遍历每个元组并在任何元组中发现 run 时中断。或者,您可以使用如下所示的短程函数 any(),这将更加 Pythonic。

https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchall.html

while True:
    if any(ran in tup for tup in output):
        print("MATCH!", ran)
        break
    else:
        print(ran)

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多