As far as I know, it should be possible to do the following in 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]])
but sadly, this is not working at all. whatever format I try to use, the $1
and $2
are never replaced with the corresponding values from the bind array.
Is there anything more i should take care of?
You should use sanitize_sql_array
in your model, like this:
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
This protects you from SQL injections.
Since you are not using named binds, you would do it like this. This works in 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']]
)
I dont understand if you are trying to use variables, but yes it is quite easy to do with variables, you have used them wrongly
Use it like this:
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]])
Where v1 and v2 are variables. Let me know if you are trying somthing else
Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.