Python,函数拒绝更新 MySQL 值?

Python, Function refuses to update a MySQL value?

我正在为我的 Raspberry Pi3 编写一个灌溉脚本,我 运行 在更新数据库时遇到了一些问题。

这是我当前的代码(在循环中):

nirrigationtime = getseconds('temp_average','humidaverage','press_Average')
print("has received data from function about how much time to add, which is currently "),nirrigationtime

#Get the current database irrigation seconds value
current_seconds = dbfetch('NIGHT_SECONDS','weather_settings')
print("this is the current value in the database for irrigation "),current_seconds

#Update the current seconds value with the additonal seconds from the getseconds function
nirriupdated = nirrigationtime + current_seconds
print("new irrigation value will be "),nirriupdated

#Update database with new night time irrigation value
try:
    dbupdate('NIGHT_SECONDS','weather_settings','nirriupdated')
    print("database updated, sleeping for 1.5min")
except:
    print("update actaully failed?")

#Sleep for 1.5 minutes
time.sleep(90)

这会在终端中产生这个结果:

has received data from function about how much time to add, which is currently  10
this is the current value in the database for irrigation  50.0
new irrigation value will be  60.0
database updated, sleeping for 1.5min

然而,问题是它永远不会将更新后的值写入数据库,而且由于更新功能在项目的所有其他部分都运行良好,我对此感到很烦恼。

这是数据库更新函数:

#This function connects to database and updates the value in the selected column in the selected table to the set new value
def dbupdate(dbcolumn,dbtable,newvalue):
    try:
        db = MySQLdb.connect("localhost","user","password","weather")
        cursor = db.cursor()
        sql = "UPDATE "+dbtable+" SET "+dbcolumn+" = "+newvalue
        try:
            cursor.execute(sql)
            db.commit()

        except:
            db.rollback()
        cursor.close()
        db.close()
        return
    except:
        print("Database connection failed")

数据库列设置为 Decimal(5,2),如前所述,该函数在其他地方运行良好。

谁能看到我看不到的东西?

看来我暂时解决了。 通过将 dbupdate() 函数从我的外部 functions.py 文件(我总是这样做并将它们导入我正在处理的文件)移动到当前文件,其余代码位于其中,并添加 nirriupdated = str (已更新)。我意识到我试图将一个整数(nirriupdated)附加到一个字符串(sql 变量),但没有用。

工作代码如下所示:

nirrigationtime = getseconds('temp_average','humidaverage','press_Average')

#Get the current database irrigation seconds value
current_seconds = dbfetch('NIGHT_SECONDS','weather_settings')

#Update the current seconds value with the additonal seconds from the getseconds function
nirriupdated = nirrigationtime + current_seconds
nirriupdated = str(nirriupdated)

#Update database with new night time irrigation value - For some reason, this doesn't work?
db = MySQLdb.connect("localhost","user","password","weather")
cursor = db.cursor()
sql = "UPDATE weather_settings SET NIGHT_SECONDS = "+nirriupdated
try:
    cursor.execute(sql)
    db.commit()

except:
    db.rollback()
cursor.close()
db.close()


#Sleep for 15 minutes
time.sleep(900)

如果有人能帮助我理解为什么当 运行 在外部 functions.py 而不是当函数写入文件时这不起作用,那么我真的很感激。特别是因为我在外部文件中使用相同的函数,在这个文件中更远一点,没有问题。就是这样的事情让我彻夜难眠..