使用Python和Snowflake处理JSON中的单引号

sbtkgmzw  于 2023-01-22  发布在  Python
关注(0)|答案(1)|浏览(189)

我尝试使用下面的python脚本将从rest API检索到的字典插入到变量数据类型的Snowflake列中

from sqlalchemy import create_engine
import urllib
import requests
import json

engine = create_engine(
'snowflake://{user}:{password}@{account_identifier}/'.format(
    user='UserName',
    password='pwd',
    account_identifier='account_Identifier'
 )
)

jval={"title":"value", "address":[{ "Road":"st xavier's","landmark":"D' Pauls"}]}

try:
    connection = engine.connect()
    results = connection.execute(
        "INSERT INTO db_name.schema_name.sqlalchemy(jval) (select PARSE_JSON('" + json.dumps(jval) + "'))").fetchone()
    print(results[0])
finally:
    connection.close()
    engine.dispose()

但最终会出现以下错误

File "C:\Users\PycharmProjects\snowflake\venv\lib\site-packages\snowflake\connector\errors.py", line 207, in default_errorhandler
raise error_class(
sqlalchemy.exc.ProgrammingError: (snowflake.connector.errors.ProgrammingError) 001003 (42000): SQL compilation error:
syntax error line 1 at position 133 unexpected 's'.
syntax error line 1 at position 134 unexpected '", "'.
[SQL: INSERT INTO db_name.schema_name.sqlalchemy(jval)  (select PARSE_JSON('{"title": "value", "address": [{"Road": "st xavier's", "landmark": "D' Pauls"}]}'))]
(Background on this error at: https://sqlalche.me/e/14/f405)

我认为这是由于字符串中存在单引号(')引起的。如何处理这个错误?即使使用snowflake.connector库也会出现同样的错误。

n9vozmp4

n9vozmp41#

使用参数绑定,以便自动处理引用。

from sqlalchemy import text 
...
results = connection.execute(
    text(
        'INSERT INTO db_name.schema_name.sqlalchemy(jval) (select PARSE_JSON(:some_json))'
    ),
    {'some_json': jval},
).fetchone()

相关问题