使用asyncpg插入大括号中的文本

huangapple go评论63阅读模式
英文:

Insert text in braces with asyncpg

问题

我有一个跟踪表:

CREATE TABLE raw_data (
	id bigserial NOT NULL,
	datetime varchar NOT NULL DEFAULT now(),
	param_id int4 NOT NULL,
	raw_data varchar NOT NULL)

我正在尝试使用 asyncpg 插入带有大括号的数据:

app['bd_conn'] = await asyncpg.create_pool(host=os.environ.get('DB_HOST'),
                                           database=os.environ.get('DB_NAME'),
                                           user=os.environ.get('DB_USER'),
                                           password=os.environ.get('DB_PASS'),
                                           max_size=5,
                                           min_size=1)
db_engine = app['bd_conn']
raw_data = "{H}"
param = "1000"
async with db_engine.acquire() as conn:
    stmt = f"""
            insert into raw_data (param, raw_data)
            values ({param}, {raw_data})
            """
    await conn.fetch(stmt)

由于 raw_data 中有大括号,所以我收到一个错误:
> 语法错误,附近为“{”

我如何修复这个错误?需要传递大括号。

英文:

I have a follow table:

CREATE TABLE raw_data (
	id bigserial NOT NULL,
	datetime varchar NOT NULL DEFAULT now(),
	param_id int4 NOT NULL,
	raw_data varchar NOT NULL)

I'm trying to insert the data with braces with asyncpg:

app['bd_conn'] = await asyncpg.create_pool(host=os.environ.get('DB_HOST'),
                                           database=os.environ.get('DB_NAME'),
                                           user=os.environ.get('DB_USER'),
                                           password=os.environ.get('DB_PASS'),
                                           max_size=5,
                                           min_size=1)
db_engine = app['bd_conn']
raw_data = "{H}"
param = "1000"
async with db_engine.acquire() as conn:
    stmt = f"""
            insert into raw_data (param, raw_data)
            values ({param}, {raw_data})
            """
    await conn.fetch(stmt)

and because of the braces in raw_data, I get an error
>syntax error at or near "{"

how can I fix this error? It is necessary to pass braces

答案1

得分: 2

您的查询容易受到SQL注入攻击 -> 安全问题。硬编码参数不是一个好做法。
相反,可以这样做:

param = 1000  # 一个整数
raw_data = "{H}"  # 一个字符串

stmt = """
       insert into raw_data (param_id, raw_data)
       values ($1, $2)
       """
await conn.execute(stmt, param, raw_data)
英文:

your query is vulnerable to SQL injections -> security issue. it's not good to hardcode parameters.
instead, do this:

param = 1000  # an integer
raw_data = "{H}"  # a string

stmt = """
       insert into raw_data (param_id, raw_data)
       values ($1, $2)
       """
await conn.execute(stmt, param, raw_data)

huangapple
  • 本文由 发表于 2023年7月12日 20:30:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76670552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定