Connect to TiDB with mysql2
TiDB is a MySQL-compatible database, and mysql2 is one of the most popular MySQL drivers for Ruby.
In this tutorial, you can learn how to use TiDB and mysql2 to accomplish the following tasks:
- Set up your environment.
- Connect to your TiDB cluster using mysql2.
- Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.
Prerequisites
To complete this tutorial, you need:
- Ruby >= 3.0 installed on your machine
- Bundler installed on your machine
- Git installed on your machine
- A TiDB cluster running
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a TiDB Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
Run the sample app to connect to TiDB
This section demonstrates how to run the sample application code and connect to TiDB.
Step 1: Clone the sample app repository
Run the following commands in your terminal window to clone the sample code repository:
git clone https://github.com/tidb-samples/tidb-ruby-mysql2-quickstart.git
cd tidb-ruby-mysql2-quickstart
Step 2: Install dependencies
Run the following command to install the required packages (including mysql2
and dotenv
) for the sample app:
bundle install
Install dependencies for existing projects
For your existing project, run the following command to install the packages:
bundle add mysql2 dotenv
Step 3: Configure connection information
Connect to your TiDB cluster depending on the TiDB deployment option you've selected.
- TiDB Serverless
- TiDB Dedicated
- TiDB Self-Hosted
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
Click Connect in the upper-right corner. A connection dialog is displayed.
Ensure the configurations in the connection dialog match your operating environment.
- Endpoint Type is set to
Public
. - Connect With is set to
General
. - Operating System matches the operating system where you run the application.
- Endpoint Type is set to
If you have not set a password yet, click Create password to generate a random password.
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .envEdit the
.env
file, set up the environment variables as follows, and replace the corresponding placeholders{}
with connection parameters in the connection dialog:DATABASE_HOST={host} DATABASE_PORT=4000 DATABASE_USER={user} DATABASE_PASSWORD={password} DATABASE_NAME=test DATABASE_ENABLE_SSL=trueSave the
.env
file.
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
Click Connect in the upper-right corner. A connection dialog is displayed.
Click Allow Access from Anywhere and then click Download CA cert to download the CA certificate.
For more details about how to obtain the connection string, refer to TiDB Dedicated standard connection.
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .envEdit the
.env
file, set up the environment variables as follows, and replace the corresponding placeholders{}
with connection parameters in the connection dialog:DATABASE_HOST={host} DATABASE_PORT=4000 DATABASE_USER={user} DATABASE_PASSWORD={password} DATABASE_NAME=test DATABASE_ENABLE_SSL=true DATABASE_SSL_CA={downloaded_ssl_ca_path}Save the
.env
file.
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .envEdit the
.env
file, set up the environment variables as follows, and replace the corresponding placeholders{}
with your own TiDB connection information:DATABASE_HOST={host} DATABASE_PORT=4000 DATABASE_USER={user} DATABASE_PASSWORD={password} DATABASE_NAME=testIf you are running TiDB locally, the default host address is
127.0.0.1
, and the password is empty.Save the
.env
file.
Step 4: Run the code and check the result
Run the following command to execute the sample code:
ruby app.rb
If the connection is successful, the console will output the version of the TiDB cluster as follows:
🔌 Connected to TiDB cluster! (TiDB version: 5.7.25-TiDB-v7.1.0)
⏳ Loading sample game data...
✅ Loaded sample game data.
🆕 Created a new player with ID 12.
ℹ️ Got Player 12: Player { id: 12, coins: 100, goods: 100 }
🔢 Added 50 coins and 50 goods to player 12, updated 1 row.
🚮 Deleted 1 player data.
Sample code snippets
You can refer to the following sample code snippets to complete your own application development.
For complete sample code and how to run it, check out the tidb-samples/tidb-ruby-mysql2-quickstart repository.
Connect to TiDB with connection options
The following code establishes a connection to TiDB with options defined in the environment variables:
require 'dotenv/load'
require 'mysql2'
Dotenv.load # Load the environment variables from the .env file
options = {
host: ENV['DATABASE_HOST'] || '127.0.0.1',
port: ENV['DATABASE_PORT'] || 4000,
username: ENV['DATABASE_USER'] || 'root',
password: ENV['DATABASE_PASSWORD'] || '',
database: ENV['DATABASE_NAME'] || 'test'
}
options.merge(ssl_mode: :verify_identity) unless ENV['DATABASE_ENABLE_SSL'] == 'false'
options.merge(sslca: ENV['DATABASE_SSL_CA']) if ENV['DATABASE_SSL_CA']
client = Mysql2::Client.new(options)
Insert data
The following query creates a single player with two fields and returns the last_insert_id
:
def create_player(client, coins, goods)
result = client.query(
"INSERT INTO players (coins, goods) VALUES (#{coins}, #{goods});"
)
client.last_id
end
For more information, refer to Insert data.
Query data
The following query returns the record of a specific player by ID:
def get_player_by_id(client, id)
result = client.query(
"SELECT id, coins, goods FROM players WHERE id = #{id};"
)
result.first
end
For more information, refer to Query data.
Update data
The following query updated the record of a specific player by ID:
def update_player(client, player_id, inc_coins, inc_goods)
result = client.query(
"UPDATE players SET coins = coins + #{inc_coins}, goods = goods + #{inc_goods} WHERE id = #{player_id};"
)
client.affected_rows
end
For more information, refer to Update data.
Delete data
The following query deletes the record of a specific player:
def delete_player_by_id(client, id)
result = client.query(
"DELETE FROM players WHERE id = #{id};"
)
client.affected_rows
end
For more information, refer to Delete data.
Best practices
By default, the mysql2 gem can search for existing CA certificates in a particular order until a file is discovered.
/etc/ssl/certs/ca-certificates.crt
for Debian, Ubuntu, Gentoo, Arch, or Slackware/etc/pki/tls/certs/ca-bundle.crt
for RedHat, Fedora, CentOS, Mageia, Vercel, or Netlify/etc/ssl/ca-bundle.pem
for OpenSUSE/etc/ssl/cert.pem
for macOS or Alpine (docker container)
While it is possible to specify the CA certificate path manually, doing so might cause significant inconvenience in multi-environment deployment scenarios, because different machines and environments might store the CA certificate in different locations. Therefore, setting sslca
to nil
is recommended for flexibility and ease of deployment across different environments.
Next steps
- Learn more usage of mysql2 driver from the documentation of mysql2.
- Learn the best practices for TiDB application development with the chapters in the Developer guide, such as: Insert data, Update data, Delete data, Query data, Transactions, and SQL performance optimization.
- Learn through the professional TiDB developer courses and earn TiDB certifications after passing the exam.
Need help?
Ask questions on TiDB Community, or create a support ticket.