Ruby 連接Mysql – MySql2
前面一章節我們介紹了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 )