如何在 MySQL中为插入和选择查询创建预准备语句?我正在使用MySQL2 gem,我的连接对象如下所示: con = Mysql2::Client.new(:host = "#{ENV['DB_HOST']}", :port = '3306', :username = "#{ENV['DB_UNAME']}", :password
con = Mysql2::Client.new(:host => "#{ENV['DB_HOST']}", :port => '3306', :username => "#{ENV['DB_UNAME']}", :password => "#{ENV['DB_PWD']}", :database => 'dbname')不幸的是,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
UPDATE
正如@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
我希望有所帮助.