Using prepared statement with MySQL2 gem?

走远了吗. 提交于 2019-12-22 10:34:59

问题


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')

回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!