【问题标题】:Cannot fetch new data in python from mysql database when new data is added添加新数据时无法从mysql数据库中获取python中的新数据
【发布时间】: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

【问题讨论】:

标签: python mysql mysql-python


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 2021-01-02
    • 2014-05-02
    • 1970-01-01
    • 2019-12-05
    • 2023-04-05
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多