【问题标题】:Python/MySQLdb troubles on Raspberry PiRaspberry Pi 上的 Python/MySQLdb 问题
【发布时间】:2012-09-14 21:34:28
【问题描述】:

我在我的树莓派上运行 python/mysqldb 时遇到了一些麻烦。这是一个非常简单的脚本,所以我不确定我错过了什么。 “SELECT * FROM ...”运行没有问题,但我似乎无法用新值更新表。脚本运行时没有抛出错误,但是当我 ctrl-C 时,它给了我这个:

Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in bound method DictCursor.__del of MySQLdb.cursors.DictCursor object at 0x19dfd90

这是我的脚本:

    dhost = "localhost"
    duser = "root"
    dname = "rpi"
    dpass = "datPassword"

    import MySQLdb

    try:
        con = MySQLdb.connect(dhost,duser,dpass,dname);
        cur = con.cursor(MySQLdb.cursors.DictCursor)

    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0],e.args[1])
        sys.exit(1)


    def websiteToSensor():
        cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
        rows = cur.fetchall()
        for row in rows:
            cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
        return

    while True:
        websiteToSensor()

有人知道为什么我的表没有更新吗?谢谢!

***编辑:解决方案***

感谢 Martijn Pieters,这是我的新 websiteToSensor() 代码:

    def websiteToSensor():
        cur = con.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
        rows = cur.fetchall()
        num = int(cur.rowcount)
        if num > 0:
            for row in rows:
                cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
            con.commit()
            cur.close()
            con.commit()
        else:
            cur.close()
            con.commit()
        return

【问题讨论】:

    标签: python mysql mysql-python raspberry-pi


    【解决方案1】:

    尝试提交您的更改:

    def websiteToSensor():
        cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
        rows = cur.fetchall()
        for row in rows:
            cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
        con.commit()
        return
    

    【讨论】:

    • 我还建议在 while 循环中使用一个小的 time.sleep
    • 我……我花了几个小时在这上面。我恨你的简单解决方案,但我爱你帮助我解决这个问题。 con.commit() 是我所需要的。非常感谢!
    • 这是给你的另一个笨蛋...这个代码只工作一次。理想情况下,这将继续轮询动态更改的 mysql 数据库并相应地更新表。但是,在脚本运行 websiteToSensor() 一次后,它并没有找到已经改变by = 'website' 的新行。任何想法为什么它不能正确读取表格?
    • 我怀疑您需要为每次运行 websiteToSensor() 创建一个新游标以获取新的事务上下文。
    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2022-01-20
    • 2016-03-14
    相关资源
    最近更新 更多