Postgresql 中的安全 SQL 动态列查询(无 Sql 注入)

发布于 2024-10-17 07:11:57 字数 647 浏览 7 评论 0原文

我使用 Rails 通过传递动态列和表名从 Postgresql 获取数据。

我无法使用 ActiveRecord,因为从 shapefile 导入的形状数据是动态的表名称和列名称。 我必须在查询中对列名使用双引号,以避免出现此类列名问题:例如“addr:city”。

def find_by_column_and_table(column_name, shape_table_name)
            sql = "SELECT \"#{column_name}\" FROM \"#{shape_table_name}\" WHERE \"#{column_name}\" IS NOT NULL"
            ActiveRecord::Base.connection.select_one(sql)
        end

2 生成sql语句的示例:

SELECT "place" FROM "shp_6c998258-32a6-11e0-b34b-080027997e00"
SELECT "addr:province" FROM "shp_6c998258-32a6-11e0-b34b-080027997e00"

我想确保查询中没有sql注入。

谁能指出我如何解决这个问题?

I'm using Rails to get data from Postgresql by passing dynamic column and table name.

I cannot use ActiveRecord because the shape data that is imported from shapefile is dynamic both table and column name.
I have to use double quote with a column name in the query to avoid problem such column name: "addr:city" for example.

def find_by_column_and_table(column_name, shape_table_name)
            sql = "SELECT \"#{column_name}\" FROM \"#{shape_table_name}\" WHERE \"#{column_name}\" IS NOT NULL"
            ActiveRecord::Base.connection.select_one(sql)
        end

2 examples of generated sql statement:

SELECT "place" FROM "shp_6c998258-32a6-11e0-b34b-080027997e00"
SELECT "addr:province" FROM "shp_6c998258-32a6-11e0-b34b-080027997e00"

I want to make sure there is no sql injection in the query.

Could anyone point me how to solve this issue?

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

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

发布评论

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

评论(1

梦在深巷 2024-10-24 07:11:58

防止注入、加快查询速度和捕获错误的推荐方法是使用位置参数或存储过程。少了一点就是自找麻烦。

The recommended way to prevent injection, speed up your query and catch errors is to use positional parameters or stored proceedures. Anything less is asking for trouble.

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