Latest web development tutorials

루비 연결 MySQL의 - MySql2

우리는 루비 DBI를 도입 이전 섹션 사용합니다. 우리의 기술 루비 연결 MySQL을보다 효율적으로 구동 mysql2의이 장에서는 또한 MySQL을 연결하는 권장되는 방법입니다.

설치 드라이브 mysql2 :

gem install mysql2

-with-mysql을 - 설정 = / 어떤 / 랜덤 / 경로 / 빈 /되는 mysql_config : 당신은 같은 -with-mysql을-구성 구성되는 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 .