Ruby Connecting to Mysql - MySql2
In the previous chapter, we introduced the use of Ruby DBI. This chapter focuses on a more efficient driver for connecting Ruby to Mysql, mysql2, which is currently recommended for this purpose.
To install the mysql2 driver:
gem install mysql2
You may need to use the --with-mysql-config
configuration to specify the path to mysql_config, such as: --with-mysql-config=/some/random/path/bin/mysql_config
.
Connection
The syntax for connecting to the database is as follows:
client = Mysql2::Client.new(:host => "localhost", :username => "root")
For more parameters, refer to http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html.
Query
results = client.query("SELECT * FROM users WHERE group='githubbers'")
Escaping Special Characters
escaped = client.escape("gi'thu\"bbe\0r's")
results = client.query("SELECT * FROM users WHERE group='#{escaped}'")
To count the number of results returned:
results.count
Iterating Through Results:
results.each do |row|
# row is a hash
# keys are database fields
# values are corresponding data from MySQL
puts row["id"] # row["id"].class == Fixnum
if row["dne"] # non-existent fields are nil
puts row["dne"]
end
end
Example
#!/usr/bin/ruby -w
require 'mysql2'
client = Mysql2::Client.new(
:host => '127.0.0.1', # Host
:username => 'root', # Username
:password => '123456', # Password
:database => 'test', # Database
:encoding => 'utf8' # Encoding
)
results = client.query("SELECT VERSION()")
results.each do |row|
puts row
end
The output of the above example is:
{"VERSION()"=>"5.6.21"}
Connection Options
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 details, visit: http://www.rubydoc.info/gems/mysql2/0.2.3/frames.