如何在postgres中转义字符串,如sql语句?

时间:2022-01-03 22:27:34

I am using Rails for a project with postgresql as the underlying database. I have a search form that needs a few modifications. Specifically, I need to ensure that if some one type in something like 'drop table allusers', I don't have a disaster on my hands. IS there anyway I can restrict the dearch to one table only and ensure that searching for something like "drop table allusers" doesn't drop the table but just return results?

我使用Rails作为底层数据库的postgresql项目。我有一个需要一些修改的搜索表单。具体来说,我需要确保如果某种类型的东西像'drop table allusers',我的手上没有灾难。无论如何,我可以将dearch仅限制在一个表中,并确保搜索“drop table allusers”之类的内容不会丢弃表但只返回结果?

2 个解决方案

#1


3  

If you're using ActiveRecord to do all the querying, and placeholders (?) wherever you have parameters to pass in, then there's nothing to worry about. The data is being escaped and user input can't change the nature of the query.

如果您使用ActiveRecord进行所有查询和占位符(?),只要您有参数传入,那么没有什么可担心的。数据正在转义,用户输入无法更改查询的性质。

http://guides.rubyonrails.org/security.html#sql-injection

#2


0  

The simplest approach would probably be to make sure that you've got your database roles set up correctly. The role that the query is executing under should only be able to do what you want it to do. It sounds like you only want the role that your web application is using to connect to the database to be able to issue SELECT statements against the allusers table. If this is the case, then create a role, and grant it the SELECT privilege on the allusers table.

最简单的方法可能是确保您已正确设置数据库角色。查询在其下执行的角色应该只能执行您希望它执行的操作。听起来您只希望Web应用程序使用的角色连接到数据库,以便能够针对allusers表发出SELECT语句。如果是这种情况,则创建一个角色,并在allusers表上授予它SELECT权限。

Some more information on database roles and granting access privileges can be found in the PostgreSQL documentation.

有关数据库角色和授予访问权限的更多信息可以在PostgreSQL文档中找到。

#1


3  

If you're using ActiveRecord to do all the querying, and placeholders (?) wherever you have parameters to pass in, then there's nothing to worry about. The data is being escaped and user input can't change the nature of the query.

如果您使用ActiveRecord进行所有查询和占位符(?),只要您有参数传入,那么没有什么可担心的。数据正在转义,用户输入无法更改查询的性质。

http://guides.rubyonrails.org/security.html#sql-injection

#2


0  

The simplest approach would probably be to make sure that you've got your database roles set up correctly. The role that the query is executing under should only be able to do what you want it to do. It sounds like you only want the role that your web application is using to connect to the database to be able to issue SELECT statements against the allusers table. If this is the case, then create a role, and grant it the SELECT privilege on the allusers table.

最简单的方法可能是确保您已正确设置数据库角色。查询在其下执行的角色应该只能执行您希望它执行的操作。听起来您只希望Web应用程序使用的角色连接到数据库,以便能够针对allusers表发出SELECT语句。如果是这种情况,则创建一个角色,并在allusers表上授予它SELECT权限。

Some more information on database roles and granting access privileges can be found in the PostgreSQL documentation.

有关数据库角色和授予访问权限的更多信息可以在PostgreSQL文档中找到。