我有生成随机数的代码,还有一个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)
'''发布于 2020-10-03 08:34:24
根据mysql python连接器文档,fetchall()返回一个元组列表。因此,当在任何元组中发现ran时,您将需要迭代每个元组并中断。或者,您可以使用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)https://stackoverflow.com/questions/64179058
复制相似问题