Ruby 連接 Mysql - MySql2

前面一章節(jié)我們介紹了 Ruby DBI 的使用。這章節(jié)我們技術(shù) Ruby 連接 Mysql 更高效的驅(qū)動(dòng) mysql2,目前也推薦使用這種方式連接 MySql。

安裝 mysql2 驅(qū)動(dòng):

gem install mysql2

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

連接

連接數(shù)據(jù)庫(kù)語(yǔ)法如下:

# 更多參數(shù)可以查看 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'")

特殊字符轉(zhuǎn)義

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

計(jì)算結(jié)果集返回的數(shù)量:

results.count

迭代結(jié)果集:

results.each do |row|
  # row 是哈希
  # 鍵值是數(shù)據(jù)庫(kù)字段
  # 值都是對(duì)應(yīng) MySQL中數(shù)據(jù)
  puts row["id"] # row["id"].class == Fixnum
  if row["dne"]  # 不存在則是 nil
    puts row["dne"]
  end
end

實(shí)例

#!/usr/bin/ruby -w
require 'mysql2'

client = Mysql2::Client.new(
	:host     => '127.0.0.1', # 主機(jī)
	:username => 'root',      # 用戶名
	:password => '123456',    # 密碼
	:database => 'test',      # 數(shù)據(jù)庫(kù)
	:encoding => 'utf8'       # 編碼
	)
results = client.query("SELECT VERSION()")
results.each do |row|
  puts row
end

以上實(shí)例運(yùn)行輸出結(jié)果為:

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

連接選項(xiàng)

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
  )

更多內(nèi)容請(qǐng)參閱:http://www.rubydoc.info/gems/mysql2/0.2.3/frames