我想制作一个python脚本,一致地检查Mysql数据库。 出现的问题是,第一次检查没有数据时,它总是说数据库中没有数据,即使我在数据库中添加了数据
但如果数据已经存在于数据库中,我会立即提取并继续
我该怎么做才能使我的python脚本一致地检查数据库,如果它找到了数据,它将停止检查数据库并继续运行
我试过在数据库中没有数据时运行它,然后将数据添加到数据库中
import mysql.connector
mydb = mysql.connector.connect(
host='localhost',
user='root',
passwd='',
database='local_data'
)
mycursor = mydb.cursor()
node_id = 123
node_id = str(node_id)
print('getting code...')
a = 0
while True:
try:
time.sleep(1)
a=a+1
print(a)
sql = "SELECT code_name FROM node_code where node_id = '"+node_id +"'"
mycursor.execute(sql)
myresult = mycursor.fetchone()
for x in myresult:
filename=x
print(filename)
break
except Exception as error:
print("Nothing in database\n")
print(error)
我期望有一个输出,它不断检查数据库,直到找到数据,然后继续
我得到了这些结果。当第二个循环运行时,数据被插入到数据库中
getting code...
1
Nothing in database
'NoneType' object is not iterable
2
Nothing in database
'NoneType' object is not iterable
3
Nothing in database
如果在我运行脚本之前数据已经在数据库中,我会得到这个
getting code...
1
server.py
这是因为事务尚未结束,除非您提交以结束该事务。 尝试通过在循环末尾执行mycursor.commit()来提交该事务
相关问题 更多 >
编程相关推荐