使用 sqlalchemy 转义单引号字符以执行 sql 查询
我正在将大量 json 数据加载到雪花中。 json 行的某些值包含单引号,当我尝试使用 parse_json 将 json 插入到雪花中时,它会返回错误。我使用 sqlalchemy 作为 python 的连接器。 这是我的代码
connection.execute(
f'insert into json_demo select parse_json( """{json.dumps(data)}""" )')
json数据示例如下:
[
{
"name": "Milka Luam",
"ID": "124",
"UnitAddressLine1": "1262 University Runa",
"UnitCity": "Jas sti'n"
},
{
"name": "Rahu Liran",
"ID": "541",
"UnitAddressLine1": "1262 University Blina",
"UnitCity": "Rish 21"
},
...
]
unity city Jas sti'n 中的单引号返回错误。 这是错误:
sqlalchemy.exc.ProgrammingError: (snowflake.connector.errors.ProgrammingError) 001003 (42000): SQL compilation error:
syntax error line 1 at position 47 unexpected 'UnitCity'.
syntax error line 1 at position 47 unexpected 'UnitCity'.
parse error line 1 at position 90,841 near '<EOF>'.
我无法手动添加转义字符,因为我正在加载大量行。
I am loading a json data with large number of into snowflake. Some values of the json row contains single quotes and it is returing an error when I am trying to insert json into snowflake using parse_json . I am using sqlalchemy as a connector from python.
Here is my code
connection.execute(
f'insert into json_demo select parse_json( """{json.dumps(data)}""" )')
The json data sample is as follows:
[
{
"name": "Milka Luam",
"ID": "124",
"UnitAddressLine1": "1262 University Runa",
"UnitCity": "Jas sti'n"
},
{
"name": "Rahu Liran",
"ID": "541",
"UnitAddressLine1": "1262 University Blina",
"UnitCity": "Rish 21"
},
...
]
The single quote in the unity city Jas sti'n is returning an error.
Here is the error:
sqlalchemy.exc.ProgrammingError: (snowflake.connector.errors.ProgrammingError) 001003 (42000): SQL compilation error:
syntax error line 1 at position 47 unexpected 'UnitCity'.
syntax error line 1 at position 47 unexpected 'UnitCity'.
parse error line 1 at position 90,841 near '<EOF>'.
I can't manually add an escape character as I am loading a large number of row.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 f 字符串插入值很容易出错并且存在安全风险。请改用 SQLAlchemy 的文本函数并绑定参数。
输出:
要执行该语句,您需要执行以下操作
Using f-strings to interpolate values is error-prone and a security risk. Use SQLAlchemy's text function and bind parameters instead.
Output:
To execute the statement, you would do
作为解决方案,您可以使用三引号
"Jas sti'n"
:"""Jas sti'n"""
或者您可以在引号前放置一个反斜杠以转义it:
"Jas sti\'n"
这两种解决方案都使 python 将
'
读取为字符串的一部分。As a solution you can either triple quote
"Jas sti'n"
:"""Jas sti'n"""
Or you can place a backslash before the quote to escape it:
"Jas sti\'n"
Both of these solutions make python read the
'
as part of the string.