Rails准备语句与select_all

时间:2012-10-06 01:41:38

标签: sql ruby-on-rails prepared-statement

据我所知,应该可以在Rails中执行以下操作:

ActiveRecord::Base.connection.select_all("SELECT MONTH(created) AS month, YEAR(created) AS year FROM orders WHERE created>=$1 AND created<=$2 GROUP BY month ORDER BY month ASC",nil,[['created',1],['created',2]])

但遗憾的是,这根本不起作用。无论我尝试使用什么格式,$1$2都不会被绑定数组中的相应值替换。

还有什么我应该照顾的吗?

3 个答案:

答案 0 :(得分:4)

您应该在模型中使用sanitize_sql_array,如下所示:

r = self.sanitize_sql_array(["SELECT MONTH(created) AS month, YEAR(created) AS year FROM orders WHERE created>=? AND created<=? GROUP BY month ORDER BY month ASC", created1, created2])
self.connection.select_all r

这可以保护您免受SQL注入。

答案 1 :(得分:1)

由于您没有使用命名绑定,您可以这样做。这适用于Rails 4.2。

ActiveRecord::Base.connection.select_all(
  "SELECT MONTH(created) AS month, YEAR(created) AS year FROM orders WHERE created>=$1 AND created<=$2 GROUP BY month ORDER BY month ASC",
  nil,
  [[nil,'2016-01-01 12:30'],[nil,'2016-01-01 15:30']]
)

答案 2 :(得分:-11)

我不明白你是否试图使用变量,但是对变量很容易,你错误地使用了它们

像这样使用:

ActiveRecord::Base.connection.select_all("SELECT MONTH(created) AS month, YEAR(created) AS year FROM orders WHERE created>=#{v1} AND created<=#{v2} GROUP BY month ORDER BY month ASC",nil,[['created',1],['created',2]])

其中v1和v2是变量。 如果你正在尝试其他事情,请告诉我

由于