MySQL
suggest changeRuby has three common ways to talk to MySQL (and MariaDB):
mysql2: the long-standing driver. A C extension that wrapslibmysqlclient. Supports prepared statements, streaming and type casting.trilogy: a newer driver from GitHub. It implements the MySQL protocol itself, so it doesn't needlibmysqlclient. It's the default for new Rails apps that use MySQL.Sequelor Active Record: higher-level libraries that sit on top of either driver and add query builders, migrations, models and connection pools.
The examples below were run against MySQL 9.7 with Ruby 4.0, mysql2 0.5.7, trilogy 2.13, Sequel 5.109 and Active Record 8.1.
Installing
mysql2 compiles against the MySQL client library, so install the development headers first:
# Debian / Ubuntu
$ sudo apt install libmysqlclient-dev # or libmariadb-dev
# macOS
$ brew install mysql-client
$ gem install mysql2 -- --with-mysql-config=$(brew --prefix mysql-client)/bin/mysql_config
On Linux a plain gem install mysql2 is usually enough once the headers are there. trilogy only needs a C compiler and OpenSSL:
$ gem install trilogy
In a Gemfile:
gem "mysql2", "~> 0.5"
# or
gem "trilogy", "~> 2.9"
The examples use a database shop and a user app that can access it:
CREATE DATABASE shop CHARACTER SET utf8mb4;
CREATE USER 'app'@'%' IDENTIFIED BY 'secret';
GRANT ALL ON shop.* TO 'app'@'%';
Connecting with mysql2
require 'mysql2'
client = Mysql2::Client.new(
host: '127.0.0.1',
port: 3306,
username: 'app',
password: ENV.fetch('MYSQL_PASSWORD', 'secret'),
database: 'shop',
encoding: 'utf8mb4',
connect_timeout: 5
)
puts client.server_info[:version]
puts Mysql2::VERSION
9.7.1
0.5.7
Always use encoding: 'utf8mb4'. MySQL's utf8 is a legacy 3-byte encoding that can't store emoji or many CJK characters.
host: 'localhost' makes libmysqlclient use the Unix socket instead of TCP; pass socket: '/path/to/mysql.sock' if it isn't in the default place. Use 127.0.0.1 to force TCP.
You can also connect with a URL-style config by parsing it yourself, but most apps read the pieces from environment variables. Never hard-code production passwords.
Creating a table
query runs any SQL statement:
client.query('DROP TABLE IF EXISTS products')
client.query(<<~SQL)
CREATE TABLE products (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sku VARCHAR(32) NOT NULL UNIQUE,
name VARCHAR(200) NOT NULL,
price DECIMAL(10,2) NOT NULL,
stock INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
SQL
Inserting with prepared statements
prepare sends the SQL to the server once, with ? placeholders. execute sends only the values, so they are never parsed as SQL:
insert = client.prepare('INSERT INTO products (sku, name, price, stock) VALUES (?, ?, ?, ?)')
insert.execute('KB-001', 'Mechanical keyboard', 129.99, 12)
puts "id=#{insert.last_id} rows=#{insert.affected_rows}"
[['MS-002', 'Wireless mouse', 39.5, 40],
['MN-003', '27" monitor', 289.0, 5],
['CB-004', 'USB-C cable ⚡', 9.99, 0]].each do |row|
insert.execute(*row)
end
insert.close
id=1 rows=1
Read last_id and affected_rows from the statement. client.last_id and client.affected_rows only report on statements run with client.query.
A statement stays open on the server until you call close or the connection ends. Prepare it once and reuse it in a loop rather than preparing it again for each row.
Querying
query returns a Mysql2::Result. It's Enumerable, and by default each row is a hash with string keys:
results = client.query('SELECT id, sku, name, price, stock, created_at FROM products ORDER BY id')
p results.fields
puts results.count
results.each do |row|
puts format('%d %-7s %-20s %8.2f %3d', row['id'], row['sku'], row['name'], row['price'], row['stock'])
end
row = results.first
p row['id'].class, row['price'].class, row['created_at'].class
["id", "sku", "name", "price", "stock", "created_at"]
4
1 KB-001 Mechanical keyboard 129.99 12
2 MS-002 Wireless mouse 39.50 40
3 MN-003 27" monitor 289.00 5
4 CB-004 USB-C cable ⚡ 9.99 0
Integer
BigDecimal
Time
Column values come back as Ruby types: INT becomes Integer, DECIMAL becomes BigDecimal (no floating-point rounding for money), DATETIME becomes Time, DATE becomes Date and NULL becomes nil. BOOLEAN is really TINYINT(1) in MySQL, so you get 1 or 0 unless you pass cast_booleans: true.
Options change the shape of the rows. You can pass them per query or to Mysql2::Client.new as defaults:
client.query('SELECT sku, price FROM products WHERE stock > 0', symbolize_keys: true).each { |r| p r }
client.query('SELECT sku, stock FROM products ORDER BY id', as: :array).each { |r| p r }
p client.query("SELECT 1.5 + 1 AS x, CAST('2024-01-02' AS DATE) AS d", cast: false).first
{sku: "KB-001", price: 0.12999e3}
{sku: "MS-002", price: 0.395e2}
{sku: "MN-003", price: 0.289e3}
["KB-001", 12]
["MS-002", 40]
["MN-003", 5]
["CB-004", 0]
{"x" => "2.5", "d" => "2024-01-02"}
0.12999e3 is how BigDecimal#inspect writes 129.99. Use to_s('F') or format to display it.
Prepared statements accept the same options as the last argument to execute:
stmt = client.prepare('SELECT name, price FROM products WHERE price BETWEEN ? AND ? ORDER BY price')
stmt.execute(10, 200, symbolize_keys: true).each { |r| p r }
upd = client.prepare('UPDATE products SET stock = stock - ? WHERE sku = ? AND stock >= ?')
upd.execute(3, 'KB-001', 3)
puts "updated: #{upd.affected_rows}"
upd.execute(3, 'CB-004', 3)
puts "updated: #{upd.affected_rows}"
{name: "Wireless mouse", price: 0.395e2}
{name: "Mechanical keyboard", price: 0.12999e3}
updated: 1
updated: 0
The second update changes nothing because CB-004 has no stock. Checking affected_rows is how you find out that a conditional UPDATE didn't match.
SQL injection and escaping
Never build SQL by putting user input straight into a string:
# DON'T: name = "x' OR '1'='1" returns every row
client.query("SELECT * FROM products WHERE name = '#{name}'")
Use a prepared statement. If you must build SQL text yourself (for example with Trilogy, or for an IN (...) list of variable length), escape every value with client.escape and keep it inside quotes:
name = "O'Reilly; DROP TABLE products; --"
puts client.escape(name)
sql = "SELECT COUNT(*) AS n FROM products WHERE name = '#{client.escape(name)}'"
puts client.query(sql).first['n']
O\'Reilly; DROP TABLE products; --
0
escape only makes values safe. Table and column names can't be escaped that way, so pick them from an allow-list in your code instead of taking them from input.
Handling errors
Every server error raises Mysql2::Error, which carries the MySQL error number and SQLSTATE:
insert = client.prepare('INSERT INTO products (sku, name, price) VALUES (?, ?, ?)')
begin
insert.execute('KB-001', 'Duplicate', 1)
rescue Mysql2::Error => e
puts e.error_number
puts e.sql_state
puts e.message
end
begin
client.query('SELECT * FROM no_such_table')
rescue Mysql2::Error => e
puts "#{e.error_number}: #{e.message}"
end
1062
23000
Duplicate entry 'KB-001' for key 'products.sku'
1146: Table 'shop.no_such_table' doesn't exist
Useful error numbers: 1062 is a duplicate key, 1213 is a deadlock (retry the transaction), 1205 is a lock wait timeout and 1451/1452 are foreign key violations. Connection problems raise the subclasses Mysql2::Error::ConnectionError and Mysql2::Error::TimeoutError.
Transactions
mysql2 has no transaction helper. Send START TRANSACTION, then COMMIT or ROLLBACK, yourself:
def transfer_stock(client, from, to, qty)
client.query('START TRANSACTION')
dec = client.prepare('UPDATE products SET stock = stock - ? WHERE sku = ? AND stock >= ?')
dec.execute(qty, from, qty)
raise "not enough stock in #{from}" if dec.affected_rows == 0
inc = client.prepare('UPDATE products SET stock = stock + ? WHERE sku = ?')
inc.execute(qty, to)
client.query('COMMIT')
rescue
client.query('ROLLBACK')
raise
ensure
dec&.close
inc&.close
end
transfer_stock(client, 'MS-002', 'CB-004', 10)
begin
transfer_stock(client, 'MN-003', 'CB-004', 100)
rescue => e
puts "rolled back: #{e.message}"
end
client.query("SELECT sku, stock FROM products WHERE sku IN ('MS-002', 'MN-003', 'CB-004') ORDER BY sku")
.each { |r| p r }
rolled back: not enough stock in MN-003
{"sku" => "CB-004", "stock" => 10}
{"sku" => "MN-003", "stock" => 5}
{"sku" => "MS-002", "stock" => 30}
Transactions only work with InnoDB tables, which is the default engine. The default isolation level is REPEATABLE READ. To read a row you're about to change and stop other transactions from changing it first, use SELECT ... FOR UPDATE inside the transaction.
Upserts
INSERT ... ON DUPLICATE KEY UPDATE inserts a row, or updates the existing one if a primary or unique key would clash. Since MySQL 8.0.19 you refer to the new values through a row alias. The older VALUES(col) syntax is deprecated:
up = client.prepare(<<~SQL)
INSERT INTO products (sku, name, price, stock) VALUES (?, ?, ?, ?) AS new
ON DUPLICATE KEY UPDATE price = new.price, stock = products.stock + new.stock
SQL
up.execute('KB-001', 'Mechanical keyboard', 119.99, 5)
puts "affected: #{up.affected_rows}"
up.execute('WC-006', 'Webcam', 79.0, 8)
puts "affected: #{up.affected_rows}"
affected: 2
affected: 1
MySQL reports 1 affected row for an insert, 2 for an update of an existing row, and 0 if the row already had those values. On MariaDB, use VALUES(price) instead of the alias.
Streaming large results
By default mysql2 loads the whole result set into memory before your block runs. For big exports, stream rows one at a time:
total = 0
client.query('SELECT price, stock FROM products', stream: true, cache_rows: false).each do |row|
total += row['price'] * row['stock']
end
puts "inventory value: #{total.to_s('F')}"
inventory value: 5041.76
You can iterate a streamed result only once, and you must read it to the end before running another query on the same connection.
Trilogy
Trilogy's API is smaller than mysql2's. It has no prepared statements, so you escape values yourself:
require 'trilogy'
client = Trilogy.new(
host: '127.0.0.1',
port: 3306,
username: 'app',
password: 'secret',
database: 'shop',
ssl: true,
ssl_mode: Trilogy::SSL_REQUIRED_NOVERIFY
)
puts client.server_version
sku = 'MS-002'
result = client.query("SELECT id, name, price, created_at FROM products WHERE sku = '#{client.escape(sku)}'")
p result.fields
p result.rows
result.each_hash { |row| p row }
client.query("INSERT INTO products (sku, name, price) VALUES ('TR-007', 'Trilogy test', 1.00)")
p client.last_insert_id
begin
client.query("INSERT INTO products (sku, name, price) VALUES ('TR-007', 'again', 1.00)")
rescue Trilogy::Error => e
puts e.class
puts e.error_code
end
client.close
9.7.1
["id", "name", "price", "created_at"]
[[2, "Wireless mouse", 0.395e2, 2026-10-17 18:45:41 UTC]]
{"id" => 2, "name" => "Wireless mouse", "price" => 0.395e2, "created_at" => 2026-10-17 18:45:41 UTC}
8
Trilogy::ProtocolError
1062
Rows come back as arrays (rows, each) or hashes (each_hash), with the same type casting as mysql2. MySQL 8 and later authenticate with caching_sha2_password by default, and that needs either TLS or a cached login. ssl: true is the simple fix. In production, use Trilogy::SSL_VERIFY_IDENTITY together with ssl_ca: so the server certificate is actually checked.
Sequel
Sequel adds a query builder, schema methods, a thread-safe connection pool and transaction blocks, and it runs on either driver (adapter: 'mysql2' or adapter: 'trilogy'):
require 'sequel'
DB = Sequel.connect(adapter: 'mysql2', host: '127.0.0.1', user: 'app', password: 'secret',
database: 'shop', encoding: 'utf8mb4', max_connections: 5)
DB.create_table!(:orders) do
primary_key :id
foreign_key :product_id, :products, type: 'bigint unsigned', null: false
Integer :quantity, null: false
column :details, :json
DateTime :created_at, null: false, default: Sequel::CURRENT_TIMESTAMP
end
products = DB[:products]
orders = DB[:orders]
expensive = products.where { price > 50 }.order(:price)
puts expensive.sql
p expensive.select_map([:sku, :price])
kb = products.first(sku: 'KB-001')
DB.transaction do
id = orders.insert(product_id: kb[:id], quantity: 2, details: '{"gift": true, "note": "Happy birthday"}')
products.where(id: kb[:id]).update(stock: Sequel[:stock] - 2)
puts "order #{id}"
end
p DB.fetch("SELECT details->>'$.note' AS note FROM orders WHERE id = ?", 1).first
p orders.join(:products, id: :product_id).select(:sku, :quantity).all
begin
products.insert(sku: 'KB-001', name: 'dup', price: 1)
rescue Sequel::UniqueConstraintViolation => e
puts e.class
end
SELECT * FROM `products` WHERE (`price` > 50) ORDER BY `price`
[["WC-006", 0.79e2], ["KB-001", 0.11999e3], ["MN-003", 0.289e3]]
order 1
{note: "Happy birthday"}
[{sku: "KB-001", quantity: 2}]
Sequel::UniqueConstraintViolation
DB.transaction commits when the block finishes and rolls back if it raises. Raise Sequel::Rollback to roll back quietly. Sequel turns MySQL error codes into exception classes such as UniqueConstraintViolation, ForeignKeyConstraintViolation and SerializationFailure, so you don't have to match error numbers. ->> is MySQL's operator for extracting a value from a JSON column as unquoted text.
Active Record without Rails
Active Record works in plain Ruby scripts too. Set adapter: to 'trilogy' or 'mysql2':
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'trilogy',
host: '127.0.0.1',
username: 'app',
password: 'secret',
database: 'shop',
encoding: 'utf8mb4',
pool: 5,
ssl: true,
ssl_mode: 'REQUIRED'
)
class Product < ActiveRecord::Base
has_many :orders
validates :sku, presence: true, uniqueness: true
end
class Order < ActiveRecord::Base
belongs_to :product
end
p Product.where('price > ?', 100).order(:price).pluck(:sku, :price)
mouse = Product.find_by!(sku: 'MS-002')
Product.transaction do
mouse.orders.create!(quantity: 3, details: { gift: false })
mouse.decrement!(:stock, 3)
end
p mouse.reload.stock
p Order.last.details
p Product.joins(:orders).group(:sku).sum(:quantity)
Product.upsert_all([{ sku: 'KB-001', name: 'Mechanical keyboard', price: 109.99 }],
update_only: [:price])
p Product.find_by(sku: 'KB-001').price
[["KB-001", 0.11999e3], ["MN-003", 0.289e3]]
27
{"gift" => false}
{"KB-001" => 2, "MS-002" => 3}
0.10999e3
Active Record reads the table schema, so details (a JSON column) comes back as a Hash. With the raw drivers you get a JSON string. upsert_all generates INSERT ... ON DUPLICATE KEY UPDATE for you. In a Rails app the same settings go in config/database.yml.
Threads and connection pools
A Mysql2::Client or Trilogy connection runs one query at a time. Don't share one between threads. Sequel and Active Record have their own pools. With a raw driver, use the connection_pool gem:
require 'mysql2'
require 'connection_pool'
POOL = ConnectionPool.new(size: 5, timeout: 3) do
Mysql2::Client.new(host: '127.0.0.1', username: 'app', password: 'secret',
database: 'shop', encoding: 'utf8mb4')
end
threads = 10.times.map do
Thread.new do
POOL.with { |client| client.query('SELECT CONNECTION_ID() AS id, SLEEP(0.1)').first['id'] }
end
end
ids = threads.map(&:value)
puts "#{ids.size} queries on #{ids.uniq.size} connections"
10 queries on 5 connections
The server closes idle connections after wait_timeout (8 hours by default). Pools usually deal with that by checking or reconnecting connections. Avoid mysql2's old reconnect: true option, because libmysqlclient has deprecated it.
Which one to use
| Library | Good for | Notes |
|---|---|---|
mysql2 |
scripts, full control over SQL | prepared statements, streaming; needs libmysqlclient |
trilogy |
Rails apps, easy installs | no client library needed; no prepared statements, escape values yourself |
| Sequel | apps without Rails, complex SQL | query builder, migrations, pool, mapped exceptions |
| Active Record | Rails, or reusing Rails models | models, validations, associations, upsert_all |
For other databases see MongoDB. To store user passwords in a users table, see Password hashing.