python,函数拒绝更新mysql值?

bmvo0sr5  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(329)

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

然而,问题是它从未将更新后的值写入数据库,而且我对它非常恼火,因为update函数在项目的所有其他部分都能很好地工作。
这是数据库更新功能:


# 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),如前所述,该函数在其他地方运行良好。。
有人能看到我看不见的东西吗?

wfsdck30

wfsdck301#

看来我暂时解决了。通过将dbupdate()函数从external functions.py文件(我总是这样做,并将它们导入到我正在处理的文件)移动到当前文件中,剩下的代码就在其中,并添加nirriupdate=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)

如果有人能帮助我理解为什么在external functions.py中运行时,而不是在文件中编写函数时,其余代码都在其中,那么我将非常感激。特别是因为我在外部文件中使用了相同的函数,在这个文件中稍微靠前一点就没有问题了。就是这样的事情让我晚上睡不着觉。。

相关问题