英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论