前面一章节我们介绍了 ruby dbi 的使用。这章节我们技术 ruby 连接 mysql 更高效的驱动 mysql2,目前也推荐使用这种方式连接 mysql。

安装 mysql2 驱动:

gem install mysql2

你需要使用 –with-mysql-config 配置 mysql_config 的路径,如: –with-mysql-config=/some/random/path/bin/mysql_config。

连接

连接数据库语法如下:

# 更多参数可以查看 http://api.rubyonrails.org/classes/activerecord/connectionadapters/mysqladapter.html
client = mysql2::client.new(:host => "localhost", :username => "root")

查询

results = client.query("select * from users where group='githubbers'")

特殊字符转义

escaped = client.escape("gi'thu\"bbe\0r's")
results = client.query("select * from users where group='#{escaped}'")

计算结果集返回的数量:

results.count

迭代结果集:

results.each do |row|
  # row 是哈希
  # 键值是数据库字段
  # 值都是对应 mysql中数据
  puts row["id"] # row["id"].class == fixnum
  if row["dne"]  # 不存在则是 nil
    puts row["dne"]
  end
end

实例

#!/usr/bin/ruby -w
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

以上实例运行输出结果为:

{"version()"=>"5.6.21"}

连接选项

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,
  :reconnect = true/false,
  :local_infile = true/false,
  :secure_auth = true/false,
  :default_file = '/path/to/my.cfg',
  :default_group = 'my.cfg section',
  :init_command => sql
  )

更多内容请参阅:http://www.rubydoc.info/gems/mysql2/0.2.3/frames