README.rdoc

Mysql2 - A modern, simple and very fast Mysql library for Ruby - binding to libmysql

The Mysql2 gem is meant to serve the extremely common use-case of
connecting, querying and iterating on results. Some database libraries out
there serve as direct 1:1 mappings of the already complex C API's
available. This one is not.

It also forces the use of UTF-8 [or binary] for the connection [and all
strings in 1.9] and uses encoding-aware MySQL API calls where it can.

The API consists of two clases:

Mysql2::Client - your connection to the database

Mysql2::Result - returned from issuing a #query on the connection. It
includes Enumerable.

Installing

gem install mysql2

You may have to specify
–with-mysql-config=/some/random/path/bin/mysql_config

Usage

Connect to a database:

# this takes a hash of options, almost all of which map directly
# to the familiar database.yml in rails
# See http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html
client = Mysql2::Client.new(:host => "localhost", :username => "root")

results.each do |row|
# conveniently, row is a hash
# the keys are the fields, as you'd expect
# the values are pre-built ruby primitives mapped from their corresponding field types in MySQL
# Here's an otter: http://farm1.static.flickr.com/130/398077070_b8795d0ef3_b.jpg
end

Or, you might just keep it simple:

client.query("SELECT * FROM users WHERE group='githubbers'").each do |row|
# do something with row, it's ready to rock
end

How about with symbolized keys?

# NOTE: the :symbolize_keys and future options will likely move to the #query method soon
client.query("SELECT * FROM users WHERE group='githubbers'").each(:symbolize_keys => true) do |row|
# do something with row, it's ready to rock
end

Async

Mysql2::Client takes advantage of the MySQL C API's (undocumented)
non-blocking function mysql_send_query for all queries. But, in
order to take full advantage of it in your Ruby code, you can do:

client.query("SELECT sleep(5)", :async => true)

Which will return nil immediately. At this point you'll probably want
to use some socket monitoring mechanism like EventMachine or even
IO.select. Once the socket becomes readable, you can do:

# result will be a Mysql2::Result instance
result = client.async_result

NOTE: Because of the way MySQL's query API works, this method will
block until the result is ready. So if you really need things to stay
async, it's best to just monitor the socket with something like
EventMachine. If you need multiple query concurrency take a look at using a
connection pool.

ActiveRecord

To use the ActiveRecord driver, all you should need to do is have this gem
installed and set the adapter in your database.yml to “mysql2”. That was
easy right? :)

EventMachine

The mysql2 EventMachine deferrable api allows you to make async queries
using EventMachine, while specifying callbacks for success for failure.
Here's a simple example: