Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ruby Connecting to Mysql - MySql2

Ruby Connecting to Mysql - MySql2

In the previous chapter we introduced the use of Ruby DBI. In this chapter we discuss the more efficient driver mysql2 for connecting Ruby to Mysql, which is currently the recommended way to connect to MySql.

Installing the mysql2 driver:

gem

install

mysql2

You need to use --with-mysql-config to configure the path to mysql_config, for example: –with-mysql-config=/some/random/path/bin/mysql_config。

Connection

The syntax for connecting to a database is as follows:

client

=

Mysql2

::

Client

.

new

(

:

host

=>

"

localhost

"

, :

username

=>

"

root

"

)

For more parameters, see 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

\0

r's

"

)

results

=

client

.

query

(

"

SELECT * FROM users WHERE group='#{escaped}'

"

)

Get the number of rows returned in the result set:



results.count

Iterating over the result set:

results

.

each

do

|

row

|

row is a hash

The keys are database fields

The values are all the corresponding data from MySQL

puts

row

[

"

id

"

]

row["id"].class == Fixnum

if

row

[

"

dne

"

]

If not present, it is 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 above example produces the following output:



{"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

/m

y

.

cfg

'

, :default_group =

'

my

.

cfg

section

'

, :init_command => sql )

For more content, please refer to:http://www.rubydoc.info/gems/mysql2/0.2.3/frames。