【问题标题】:Error while updating json column in postgresql with python使用python更新postgresql中的json列时出错
【发布时间】:2019-03-25 02:24:03
【问题描述】:

当尝试使用 psycopg2 在 Postgres 中更新 json 类型的列时,会出现以下错误: psycopg2.ProgrammingError: can't adapt type 'dict'

我正在运行这段代码:

self.cursor.execute("UPDATE tb_games SET infos_json = %s WHERE id = 10", 
                    (json.dumps({'v1':'a','v2':'b'})))
conexao.commit()

我传递给 json.dumps() 的 json 是有效的,我已经测试过了。有谁知道我可能做错了什么?

【问题讨论】:

    标签: python postgresql


    【解决方案1】:

    execute 的第二个参数应该是 sequence, such as a tuple

    self.cursor.execute("UPDATE tb_games SET infos_json = %s WHERE id = 10", 
                        (json.dumps({'v1':'a','v2':'b'}),) )
    

    注意(json.dumps({'v1':'a','v2':'b'}),) 中的逗号使表达式成为一个元组(包含一个元素)。没有它,括号中的整个表达式将被评估为一个字符串。

    In [52]: type((json.dumps({'v1':'a','v2':'b'}),))
    Out[52]: tuple
    
    In [53]: type((json.dumps({'v1':'a','v2':'b'})))
    Out[53]: str
    

    要确保在与游标self.cursor 关联的连接上调用commit, 打电话可能会更好

    self.cursor.connection.commit()
    

    而不是

    conexao.commit()
    

    或者,使用connection as a context manager

    with conexao:
        with conexao.cursor() as cursor:
            cursor.execute("UPDATE tb_games SET infos_json = %s WHERE id = 10", 
                            (json.dumps({'v1':'a','v2':'b'}),) )
    

    当 Python 的执行流程离开外部 with 块时,事务被提交,除非出现错误,在这种情况下事务被回滚。这使得更容易 始终执行commit/rollback 行为,而无需编写大量样板代码。

    【讨论】:

    • 谢谢!解决了一个参数!但是现在当我传递第二个参数时,它给出了同样的错误。我正在尝试运行以下代码: self.cursor.execute("UPDATE tb_games set infos_json = %s WHERE id = %s", (json.dumps({'v1':'a','v2':' b'}), id_game))
    • 该命令对我来说看起来不错。您可以尝试将 print(self.cursor.mogrify("UPDATE tb_games SET infos_json = %s WHERE id = %s", (json.dumps({'v1':'a','v2':'b'}), id_game)))inspect the SQL 发送到 PostgreSQL。
    猜你喜欢
    • 2019-10-14
    • 2016-02-11
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多