簡體   English   中英

Psycopg2 中嵌套大括號 SQL 組成查詢

[英]Nested curly brackets in Psycopg2 SQL Composition query

我正在嘗試使用Pycopg2SQL 字符串組合創建查詢,我需要在查詢中使用大括號來更新 jsonb 列中的鍵值。 是這樣的:

update myschema.users set data = jsonb_set(data, '{someId}', '100')

這就是我嘗試使用 Python 中的 Sql 組合字符串編寫此查詢的方式:

statement = SQL(
    "UPDATE {schema}.{table} set data = jsonb_set(data, '{{key}}', '{value}') {where};"
).format(
    schema=Identifier(schema_var),
    table=Identifier(table_var),
    key=SQL(id_key),
    value=SQL(id_value),
    where=SQL(where),
)

但是通過運行它,一個名為key的新鍵將被添加到 jsonb 值中。 如果我嘗試像這樣只用一對大括號運行它:

statement = SQL(
    "UPDATE {schema}.{table} set data = jsonb_set(data, '{key}' ...." # The rest is the same

我收到此錯誤:

數組值必須以“{”或維度信息開頭

我怎樣才能解決這個問題?

為了解決這個問題,我需要使用三個嵌套的大括號,如下所示:

statement = SQL(
    "UPDATE {schema}.{table} set data = jsonb_set(data, '{{{key}}}' ...." # The rest is the same

這樣, someId鍵實際上會在數據庫中得到更新。

你想多了。

加載數據到表中:

json_import
                              Table "public.json_import"
  Column   |  Type   | Collation | Nullable |                 Default                 
-----------+---------+-----------+----------+-----------------------------------------
 id        | integer |           | not null | nextval('json_import_id_seq'::regclass)
 jsonb_fld | jsonb   |           |          | 


insert into json_import values (1, '{"test": "dog"}'::jsonb);

 select * from json_import;                                  
 id |    jsonb_fld    
----+-----------------
  1 | {"test": "dog"}


import psycopg2
from psycopg2 import sql

con = psycopg2.connect("dbname=test user=postgres host=localhost port=5432")
cur = con.cursor()

sql_str = sql.SQL('update {table} set jsonb_fld = jsonb_set(jsonb_fld,
%(key)s, %(val)s) where id = 1').format(table=sql.Identifier('json_import'))

cur.execute(sql_str, {'key': '{test}', 'val': '"cat"'})

con.commit()

select * from json_import;  
 id |    jsonb_fld    
----+-----------------
  1 | {"test": "cat"}

jsonb_set()的值應該作為參數傳遞,而不是作為組合過程的一部分。

更新

使用相同的sql_str並將值分配給變量。

key_val = '{test}'
fld_val = '"cat"'

cur.execute(sql_str, {'key': key_val, 'val': fld_val})

con.commit()

cur.execute("select * from json_import")
cur.fetchone()

(1, {'test': 'cat'})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM