如何在MySQL中为insert
和select
查询创建预准备语句?我正在使用MySQL2 gem,我的连接对象如下所示:
con = Mysql2::Client.new(:host => "#{ENV['DB_HOST']}", :port => '3306', :username => "#{ENV['DB_UNAME']}", :password => "#{ENV['DB_PWD']}", :database => 'dbname')
答案 0 :(得分:6)
不幸的是,mysql2 gem尚未准备好语句支持。贡献者计划在不久的将来添加这样的功能,正如我们从Pull Request讨论中看到的那样:
https://github.com/brianmario/mysql2/pull/289
如果您必须在您的应用程序中准备好语句,我建议您阅读Sequel,它对准备好的语句和绑定变量有非常好的支持:
https://github.com/jeremyevans/sequel
http://sequel.jeremyevans.net/rdoc/files/doc/prepared_statements_rdoc.html
<强>更新强>
正如@lulalala所述,从版本 0.4.0开始 MySQL2 gem支持预备语句:
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
我希望有所帮助。
答案 1 :(得分:1)
您也可以使用mysql2-cs-bind gem,它是mysql2的一个瘦包装,它添加了预备语句功能: https://github.com/tagomoris/mysql2-cs-bind
它提供了接受语句参数的xquery
方法:
require 'mysql2-cs-bind'
client = Mysql2::Client.new(...)
client.xquery('SELECT x,y,z FROM tbl WHERE x=? AND y=?', val1, val2) #=> Mysql2::Result