【问题标题】:python flask cursors.execute() of INSERT and DELETE doesn't workINSERT 和 DELETE 的 python flask cursors.execute() 不起作用
【发布时间】:2015-10-13 18:36:12
【问题描述】:

我是 python 开发的新手,我正在尝试使用以下函数更新数据库,但遗憾的是它不起作用:

def db_update_favourite(user_id, id_layer,favourite):
    connection = g.db
    cursor = connection.cursor()
    cursor.execute(SCHEMA)
    chiave="favourite_layers";

    if(favourite):
        query = ("""INSERT INTO users_properties (id_user,chiave,index,val_bigint)
                VALUES(%s,%s,(SELECT max(index)+1 from users_properties),%s)
            """)
    else:
        query = ("""DELETE FROM users_properties
                WHERE  id_user=%s AND chiave=%s AND val_bigint=%s
            """)


    print query %(user_id,chiave,id_layer)
    try:
        res= cursor.execute(query, (user_id,chiave,id_layer))
    except Exception as e:
        print e
    print res
    print cursor.rowcount
    return cursor.rowcount>=1

如果我去检查数据库,我发现这个函数根本没有改变数据库。

如果相反,我使用 psql 手动尝试这两个查询,它们按预期工作。

如您所见,我尝试调试但 res 为 None,未触发异常且行数始终为 1。

还有其他方法可以执行类似的查询并且它们都有效,可以是什么?关于如何进一步调试它的任何其他想法,否则?

附言 我正在使用 pg8000,因为服务器不是我的,并且已经存在的代码使用该库。

【问题讨论】:

  • 你启用autocommit了吗?
  • 我想我现在用 \set autocommit off 禁用了它,但它仍然不起作用
  • 它在您的代码中关闭,您需要显式调用提交,否则您的更改将不会保存到数据库中。 connection.commit()
  • 你是我的救星!非常感谢!

标签: python database postgresql flask pg8000


【解决方案1】:

在关闭连接之前使用connection.commit()g.db.commit()

【讨论】:

  • 被选为最佳答案,因为@dirn 刚刚发表了评论,这样更容易看到。不过他已经回答了。
猜你喜欢
  • 2015-10-16
  • 1970-01-01
  • 2022-01-27
  • 1970-01-01
  • 2015-02-08
  • 2021-11-29
  • 2018-07-19
  • 2014-09-28
  • 1970-01-01
相关资源
最近更新 更多