Connector/Ruby Guide
Quickstart guide for Connector/Ruby
Quickstart Guide: MariaDB Connector/Ruby (using mysql2 gem)
While there isn't a separate "MariaDB Connector/Ruby" gem, the widely used mysql2 gem serves as the primary and highly compatible Ruby client for connecting to both MariaDB and MySQL databases. It provides a robust API for database interactions in Ruby applications.
The mysql2 gem provides a Ruby interface to the MariaDB/MySQL C client library (either libmysqlclient or MariaDB Connector/C). It allows Ruby applications to execute SQL queries, fetch results, and manage database connections efficiently. It's available on .
2. Installation
Before installing the mysql2 gem, you might need to install development libraries for MariaDB Connector/C or MySQL Client on your system.
a. Install System Dependencies (e.g., on Debian/Ubuntu):
On other systems (Fedora, CentOS, macOS), the package names might differ (e.g., mariadb-devel, mysql-devel).
b. Install the mysql2 gem:
Once the system dependencies are in place, install the gem using Bundler (recommended for Rails/Gemfile projects) or directly via gem install:
Here's how to connect to MariaDB and perform common database operations using the mysql2 gem:
a. Connect to the Database:
Replace localhost, 3306, your_username, your_password, and your_database_name with your actual database details.
b. Execute a SELECT Query:
The results object behaves like an enumerable, allowing you to iterate over rows. Column names are accessible as hash keys.
c. Execute INSERT/UPDATE/DELETE Queries:
For data manipulation, use query. For safety, always use prepared statements or proper escaping for user-provided input.
d. Prepared Statements (Recommended for security and performance):
Prepared statements allow you to separate the SQL query structure from the data, preventing SQL injection and improving performance for repeated queries.
Before Running:
Ensure you have a MariaDB server running and a database/table set up.
Replace placeholder values with your actual database credentials and table/column names.
Important Notes:
Error Handling: Always wrap your database operations in begin...rescue...end blocks to catch Mysql2::Error exceptions.
Connection Closing: Ensure your Mysql2::Client connection is closed using client.close in a ensure block to release database resources.
Further Resources: