在 mysql 数据库中找不到与 python 匹配的结果,即使结果在 table 中
No match found in mysql DB with python even though results are in the table
我有生成随机数的代码,还有一个 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)
'''
根据 mysql python 连接器文档,fetchall() returns 元组列表。因此,您需要遍历每个元组,并在任何元组中发现 运行 时中断。或者,您可以使用 short-cicuiting 函数 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)
我有生成随机数的代码,还有一个 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)
'''
根据 mysql python 连接器文档,fetchall() returns 元组列表。因此,您需要遍历每个元组,并在任何元组中发现 运行 时中断。或者,您可以使用 short-cicuiting 函数 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)