ruby mysql2
1. mysql2连接选项
Mysql2::Client.new( :host, :username, :password, :port, :database, :socket = '/path/to/mysql.sock', :flags = REMEMBER_OPTIONS | LONG_PASSWORD | LONG_FLAG | TRANSACTIONS | PROTOCOL_41 | SECURE_CONNECTION | MULTI_STATEMENTS, :encoding = 'utf8', :read_timeout = seconds, :write_timeout = seconds, :connect_timeout = seconds, :connect_attrs = {:program_name => $PROGRAM_NAME, ...}, :reconnect = true/false, :local_infile = true/false, :secure_auth = true/false, :ssl_mode = :disabled / :preferred / :required / :verify_ca / :verify_identity, :default_file = '/path/to/my.cfg', :default_group = 'my.cfg section', :init_command => sql )
2.使用实例
require 'mysql2' client = Mysql2::Client.new( :host => '127.0.0.1', # 主机 :username => 'root', # 用户名 :password => '123456', # 密码 :database => 'test', # 数据库 :encoding => 'utf8' # 编码 ) results = client.query("SELECT VERSION()") results.each do |row| puts row end
puts results.count #结果集中的条数
这里results的class是Mysql2::Result,这个结果集mixin了Enumerable模块;我们可以通过迭代对其进行访问
支持Prepared statements
statement = @client.prepare("SELECT * FROM users WHERE login_count = ?") result1 = statement.execute(1) result2 = statement.execute(2) statement = @client.prepare("SELECT * FROM users WHERE last_login >= ? AND location LIKE ?") result = statement.execute(1, "CA") statement = @client.prepare("SELECT * FROM users WHERE last_login >= ? AND location LIKE ?") result = statement.execute(1, "CA", :as => :array)