How do I create prepared statements for insert
and select
queries in MySQL? I am using the MySQL2 gem, and my connection object looks like this:
con = Mysql2::Client.new(:host => "#{ENV['DB_HOST']}", :port => '3306', :username => "#{ENV['DB_UNAME']}", :password => "#{ENV['DB_PWD']}", :database => 'dbname')
Unfortunately, mysql2 gem does not have prepared statement support yet. The contributors are planning to add such a feature in a near future, as we can see by this Pull Request discussion:
https://github.com/brianmario/mysql2/pull/289
If you must have prepared statements in your application, I would recommend you to read about Sequel, which has a very nice support for prepared statements and bound variables:
https://github.com/jeremyevans/sequel
http://sequel.jeremyevans.net/rdoc/files/doc/prepared_statements_rdoc.html
UPDATE
As mentioned by @lulalala starting on version 0.4.0 MySQL2 gem supports prepared statements:
statement = @client.prepare("SELECT * FROM users WHERE login_count = ?")
result1 = statement.execute(1) # Binds the value 1 to the placeholder
result2 = statement.execute(2) # Binds the value 2 to the placeholder
statement = @client.prepare("SELECT * FROM users WHERE last_login >= ? AND location LIKE ?")
result = statement.execute(1, "CA") # Binds 1 and 'CA' to the placeholders, respectively
I hope that helps.
You may also use mysql2-cs-bind gem, a thin wrapper of mysql2 which adds prepared statement feature: https://github.com/tagomoris/mysql2-cs-bind
It provides xquery
method that accepts arguments for the statement:
require 'mysql2-cs-bind'
client = Mysql2::Client.new(...)
client.xquery('SELECT x,y,z FROM tbl WHERE x=? AND y=?', val1, val2) #=> Mysql2::Result
来源:https://stackoverflow.com/questions/21719003/using-prepared-statement-with-mysql2-gem