添加新数据后,无法从mysql数据库中获取python中的新数据

时间:2019-05-08 11:54:32

标签: python mysql mysql-python

我想制作一个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

1 个答案:

答案 0 :(得分:0)

这是因为除非您提交结束该事务的提交,否则事务尚未结束。 尝试通过在循环结束时执行mycursor.commit()来提交该事务