Python / MySQLdb在Raspberry Pi上遇到了麻烦

时间:2012-09-22 21:29:40

标签: python mysql mysql-python raspberry-pi

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

  

异常_mysql_exceptions.ProgrammingError:(2014,“命令不同步;你现在无法运行此命令”)绑定方法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,这是我的新网站Tosensor()代码:

    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

1 个答案:

答案 0 :(得分: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