我想知道如何在一般的SQL查询中转义?
和:
。
这些只是任意的例子:
Post.find_by_sql ["SELECT title, author, content FROM post where author = ? AND RIGHT(content, 1) = '?'", @author]
(查找帖子以
?
结尾)Post.find_by_sql ["SELECT title, author, content FROM post where author = :author AND title LIKE 'Foo:bar%'", {author:@author}]
(查找帖子以
foo:bar
开头)我不是在问如何逃逸来防止注射。当我使用参数化查询时,rails会将
?
和:some_var
视为参数。但是如果我想使用?
和:stuff
作为查询的一部分呢?如何转义它们,以便Rails将它们视为字符串,而不是试图找到匹配的参数?我知道一个解决方案是编写以下两个查询:
Post.find_by_sql ["SELECT title, author, content FROM post where author = ? AND RIGHT(content, 1) = ?", @author, '?']
Post.find_by_sql ["SELECT title, author, content FROM post where author = :author AND title LIKE CONCAT(:name, '%')", {author:@author, name:'foo:bar'}]
但有没有更优雅的方式呢?
最佳答案
参见quote
方法:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Quoting.html#method-i-quote
我知道你说的是“一般”,但是上面两个查询可以用ActiveRecord编写,这样你就可以避免自己引用。