清理 psycopg2 的 SQL fstring 查询

发布于 2025-01-19 18:28:07 字数 454 浏览 2 评论 0原文

我迭代地构建了我的SQL查询以这样执行:


        sql = "SELECT * FROM txs "

        param_values = []
        if params:
            sql += f"WHERE name=%s" 
            param_values.append(params.name)
        
        ...

        with _psql_connection() as c:
            c.execute(sql, (*param_values)
            return c.fetchall()

似乎我使用FString附加名称是可注射的,我不确定这里的解决方案是什么。 c.execute不应该(sql,(*param_values)已经对输入进行了消毒?

I'm iteratively building up my SQL query to execute as such:


        sql = "SELECT * FROM txs "

        param_values = []
        if params:
            sql += f"WHERE name=%s" 
            param_values.append(params.name)
        
        ...

        with _psql_connection() as c:
            c.execute(sql, (*param_values)
            return c.fetchall()

It seems as though me using the fstring to append the name is injectable, and I'm not sure what the right solution here is. Shouldn't c.execute(sql, (*param_values) sanitize the input already ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

桃酥萝莉 2025-01-26 18:28:07
import psycopg2 
from psycopg2 import sql 
con = psycopg2.connect(dbname="test", host='localhost', user='postgres')

params = True
sql_str = sql.SQL("SELECT * FROM txs ")
where_str = sql.SQL("WHERE name=%s")

param_values = []
if params:
    sql_str = sql.Composed([sql_str, where_str])
    param_values.append(params.name)

print(sql_str.as_string(con))
SELECT * FROM txs WHERE name=%s


with con.cursor() as c:
  c.execute(sql_str, param_values)
  return c.fetchall()
import psycopg2 
from psycopg2 import sql 
con = psycopg2.connect(dbname="test", host='localhost', user='postgres')

params = True
sql_str = sql.SQL("SELECT * FROM txs ")
where_str = sql.SQL("WHERE name=%s")

param_values = []
if params:
    sql_str = sql.Composed([sql_str, where_str])
    param_values.append(params.name)

print(sql_str.as_string(con))
SELECT * FROM txs WHERE name=%s


with con.cursor() as c:
  c.execute(sql_str, param_values)
  return c.fetchall()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文