我想制作一个持续检查 Mysql 数据库的 python 脚本。 出现的问题是第一次检查没有数据它一直说数据库中没有数据,即使我将数据添加到数据库中也是如此。
但如果数据已经存在于数据库中,我会立即获取并继续。
我该怎么做才能使我的 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() 来提交该事务
关于python - 添加新数据时无法从 mysql 数据库中获取 python 中的新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56040228/