Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 转义';:';和'';在Rails中的参数化SQL查询中_Mysql_Sql_Ruby On Rails - Fatal编程技术网

Mysql 转义';:';和'';在Rails中的参数化SQL查询中

Mysql 转义';:';和'';在Rails中的参数化SQL查询中,mysql,sql,ruby-on-rails,Mysql,Sql,Ruby On Rails,我想知道如何在SQL查询中转义?和: 这些只是武断的例子: Post.find_by_sql ["SELECT title, author, content FROM post where author = ? AND RIGHT(content, 1) = '?'", @author] (查找帖子以?结尾) (查找帖子以foo:bar开头) 我不是在问如何逃跑来防止注射。我在问,当我使用参数化查询时,rails会将?和:一些变量作为参数。但是如果我想使用?和:stuff作为查询的一部分,该怎

我想知道如何在SQL查询中转义

这些只是武断的例子:

Post.find_by_sql ["SELECT title, author, content FROM post where author = ? AND RIGHT(content, 1) = '?'", @author]
(查找帖子以
结尾)

(查找帖子以
foo:bar
开头)

我不是在问如何逃跑来防止注射。我在问,当我使用参数化查询时,rails会将
:一些变量
作为参数。但是如果我想使用
: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'}]

但是还有更优雅的方法吗?

请参见
引用方法:


我知道你说的是“一般”,但上面两个查询可以使用ActiveRecord编写,这样你就不用自己引用了。

你能解释更多吗?在这两个例子中,我不知道如何使用引号。其目的不是阻止SQL注入。问题是rails会看到什么?和:条作为参数而不是字符串。我不明白你的问题……:)问题是rails会看到什么?和:将条作为参数而不是字符串。但我希望rails将它们视为字符串。您可以使用内置函数,如Post.where(“author=\?和title,如“%”?%,@title)
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'}]