Ruby connection Mysql - MySql2

In the previous section we introduced the use of Ruby DBI. This section of our technology Ruby connects Mysql more efficient driver mysql2, it is also recommended to connect to MySql.

Install the mysql2 driver:

gem install mysql2

You need to configure the path to mysql_config with –with-mysql-config, such as: –with-mysql-config=/some/random/path/bin/mysql_config.


The syntax of the connection database is as follows:

client = Mysql2::Client.new(:host => "localhost", :username => "root ")


results = Client.query( "SELECT * FROM users WHERE group='githubbers' ")

Special character escaping

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

Calculate the number returned by the result set:


Iterative result set:

results. Each do |row| # row is hash # key-values are database fields # Values are for MySQL data puts row["id"] # row["id"].class == Fixnum if row["dne"] # If it does not exist, it is nil puts row["dne"] end end


#!/usr/bin/ruby -w require 'mysql2' client = Mysql2::Client.new( :host => '', # 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 above example runs the output as:


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 )

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.