The best Ruby connection Mysql - MySql2 Tutorial In 2024, In this tutorial you can learn Ruby connection Mysql - MySql2
The previous section we introduced the Ruby DBI uses. This chapter of our technical Ruby connection Mysql more efficient drive mysql2, is also the recommended way to connect MySql.
Installation mysql2 drive:
gem install mysql2
You need to use the -with-mysql-config configuration mysql_config path, such as: -with-mysql-config = / some / random / path / bin / mysql_config.
Database connection syntax is as follows:
# 更多参数可以查看 http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/MysqlAdapter 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}'")
The results set the number of returns:
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
Run the above example output is:
{"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 )
For more information, please refer to: http://www.rubydoc.info/gems/mysql2/0.2.3/frames .