繁体   English   中英

在Raspberry Pi3上将数据从Python存储到MySQL,无法获取和使用相同的数据

[英]Storing data from Python to MySQL on Raspberry Pi3, Trouble fetching and using the same data

我一直在尝试使用Python脚本将值保存到MySQL数据库中,并且一直进展顺利。 我存储的数据是表weather_settings NIGHT_SECONDS列中的整数60。 但是,当我尝试将数据输出到另一个脚本中时,似乎得到了值((60L,),) 我试过谷歌搜索,我没有运气。 谁能帮助我理解我做错了什么?

这是我的代码:

def gettime():
    db = MySQLdb.connect("localhost","user","pass","weather")
    cursor = db.cursor()

    try:
        sql = "select NIGHT_SECONDS from weather_settings"
        cursor.execute(sql)
        global delay
        delay = cursor.fetchall()
        print("Data fetched from MySQL")
        #print(delay)
        print(delay)

    except:
        print("Database fetching failed")

    cursor.close()
    db.close()  

这是最终结果:

Data fetched from MySQL
((60L,),)

如果我尝试在time.sleep(delay)使用此值,我会得到:

TypeError: a float is required

所以我尝试了这个:

delay = float(delay) 

这也没用。

你的问题是fetchall()返回一个行元组,它们本身是列值的元组,所以你需要像delay[0][0]那样访问它。

这可以使用fetchone()简化一下:

weather_settings_row = cursor.fetchone()
delay = float(weather_settings_row[0])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM