I use MySQL DB and MySQL2 as adapter.
I want to execute custom sql-statements in Rails.
I need a method that would allow to prepare sql-statements like in PHP, like this:
stmt = prepare("INSERT INTO tab (col1, col2) VALUES (?, ?)", ["foo", "bar"])
I found, though, that neither ActiveRecord nor MySQL2 have no such methods.
But I found that there are several exec_*
methods in ActiveRecord::ConnectionAdapters::AbstractAdapter and I think they are exactly for my task but don't know how to use them, their API documentation has very little info:
exec_insert(sql, name, binds)
Executes insert sql statement in the context of this connection using binds as the bind substitutes. name is the logged along with the executed sql statement.
I've tired this
sql = "INSERT INTO tab (col1, col2) VALUES (?, ?)"
r = ActiveRecord::Base.connection().exec_insert(sql, "someName", [10, "foo"])
puts r
But got an error:
`query': Mysql2::Error: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use near '?, ?)'
So how to use these methods? What is a name
attribute? What is a type of a bind
parameter? How to write sql-statement, what to put instead of ?
?
UPD:
I've written prepare
method to use in Rails. See in github.