Python,Function拒绝更新MySQL值?

时间:2018-06-16 11:22:07

标签: mysql python-3.x raspberry-pi3

我正在为我的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")

数据库列设置为十进制(5,2),如上所述,该函数在其他地方运行良好..

任何人都可以看到我无法看到的东西吗?

1 个答案:

答案 0 :(得分:0)

所以我似乎暂时解决了它。 通过将dbupdate()函数从我的外部functions.py文件(我总是将其导入并将其导入到我正在处理的文件中)移动到当前文件,其余代码就在其中,并添加nirriupdated = str (nirriupdated)。我意识到我试图将一个整数(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中运行时它不起作用,而不是在文件中写入函数的时候剩下的代码就在那里我真的很感激。特别是因为我在外部文件中使用相同的功能,在这个文件中更远一点没有问题。这样的事情让我夜不能寐。