Python“long”类型不是iterab

2024-07-08 10:02:44 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我基本上是使用python函数从awsrds中的MySQL DB实例收集数据,连接到数据库是成功的,但是只要调用下面的函数,它就会返回一个错误

'long' type is not iterable.

def getLastData():
    for row in cur.execute("SELECT * FROM weather ORDER BY timestamp DESC LIMIT 1"):
        time = str(row[1])
        temp = row[2]
        hum = row[3]
        press = row[4]

    return time, temp, hum, press

这是天气表的样子

+-------------+------------+------+-----+---------+----------------+
| Field       | Type       | Null | Key | Default | Extra          |
+-------------+------------+------+-----+---------+----------------+
| id          | int(11)    | NO   | PRI | NULL    | auto_increment |
| timestamp   | datetime   | YES  |     | NULL    |                |
| temperature | double     | YES  |     | NULL    |                |
| humidity    | double     | YES  |     | NULL    |                |
| pressure    | double     | YES  |     | NULL    |                |
| not_raining | tinyint(4) | YES  |     | NULL    |                |
+-------------+------------+------+-----+---------+----------------+

我想知道我的代码有什么问题,任何帮助都是感激的。你知道吗


Tags: 实例函数dbtimemysqlnotnulltemp
2条回答

您没有正确地使用游标对象。你知道吗

要执行查询,请调用execute()方法,然后在光标上迭代或调用各种方法,如fetchone()fetchmany()cur.execute()的返回值不是可以迭代的。你知道吗

要将代码更改为在光标上迭代,请在一行上调用cur.execute(...),然后在下一行上迭代光标:

def getLastData():
    cur.execute("SELECT * FROM weather ORDER BY timestamp DESC LIMIT 1")
    for row in cur:
        time = str(row[1])
        temp = row[2]
        hum = row[3]
        press = row[4]

    return time, temp, hum, press

然而,虽然只要表中有一些天气数据,这看起来就可以工作,但是如果这个表是空的,它将以NameError失败,因为没有要迭代的行,因此变量timetemphumpress将是未定义的。你知道吗

最好调用cur.fetchone(),因为我们最多只需要一行。如果有数据要读取,则返回数据行;如果没有,则返回None。然后,我们可以根据需要处理错误情况:

def getLastData():
    cur.execute("SELECT * FROM weather ORDER BY timestamp DESC LIMIT 1")
    row = cur.fetchone()
    if row is None:
        # TODO change this if necessary
        raise ValueError("No weather data found")
    else:
        time = str(row[1])
        temp = row[2]
        hum = row[3]
        press = row[4]

        return time, temp, hum, press

cursor.execute()仅在提供multi=True选项时返回迭代器。你知道吗

for row in cur.execute("SELECT * FROM weather ORDER BY timestamp DESC LIMIT 1", multi=True):

参见documentation。你知道吗

相关问题 更多 >

    热门问题