Using prepared statement with MySQL2 gem?

久未见 提交于 2019-12-05 19:22:36

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