【发布时间】:2019-09-26 03:46:11
【问题描述】:
我想制作一个始终检查 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
【问题讨论】:
-
在 while 循环结束时尝试 mycursor.commit()
-
这告诉我为什么...支持其他人说做 conn.commit() stackoverflow.com/questions/21974169/…
标签: python mysql mysql-python