在 Raspberry Pi3 上存储从 Python 到 MySQL 的数据,获取和使用相同数据时遇到问题

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

我一直在尝试获取 Python 脚本以将值保存到 MySQL 数据库中,并且进展顺利。 我存储的数据是tableweather_settingsNIGHT_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() returns 行的元组,它们本身是列值的元组,所以你需要像 delay[0][0].[=14 一样访问它=]

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

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