A simple ruby app that connects to a TiDB database cluster and performs basic CRUD operations with mysql2 driver.
The following guide will show you how to connect to the TiDB cluster with Ruby driver mysql2 and perform basic SQL operations like create, read, update, and delete.
Notice:
TiDB is a MySQL-compatible database, which means you can connect to a TiDB cluster in your application using the familiar driver/ORM framework from the MySQL ecosystem.
The only difference is that if you connect to a TiDB Serverless cluster with public endpoint, you MUST enable TLS connection on the mysql2 driver.
To complete this guide, you need:
If you don’t have a TiDB cluster yet, please create one with one of the following methods:
This section demonstrates how to run the sample application code and connect to TiDB with mysql2
driver.
Run the following command to clone the sample code locally:
git clone https://github.com/tidb-samples/tidb-ruby-mysql2-quickstart.git
cd tidb-ruby-mysql2-quickstart
Run the following command to install the dependencies (including the mysql2
package) required by the sample code:
bundle install
For your existing project, run the following command to install the packages:
mysql2
: The ruby MySQL driver for the database connection and SQL operations.dotenv
: The utils package to loading environment variables from the .env
file.bundle add mysql2 dotenv
You can obtain the database connection parameters on TiDB Cloud’s Web Console through the following steps:
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.
In the connection dialog, select General
from the Connect With dropdown and keep the default setting of the Endpoint Type as Public
.
If you have not set a password yet, click Create password to generate a random password.
Copy the connection parameters shown on the code block.
You can obtain the database connection parameters on TiDB Cloud’s Web Console through the following steps:
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.
Create a traffic filter for the cluster.
Under Step 2: Download TiDB cluster CA in the dialog, click Download TiDB cluster CA for TLS connection to TiDB clusters.
Under Step 3: Connect with a SQL client in the dialog, select General
from the Connect With dropdown and select Public
from the Endpoint Type dropdown.
Copy the connection parameters shown on the code block.
Prepare the following connection parameters for your cluster:
127.0.0.1
).4000
).root
)..env.example
file to the .env
file..env
file, and replace the placeholders for <host>
, <user>
, and <password>
with the copied connection parameters.DATABASE_ENABLE_SSL
to true
to enable a TLS connection. (Required for public endpoint)DATABASE_HOST=<host>
DATABASE_PORT=4000
DATABASE_USER=<user>
DATABASE_PASSWORD=<password>
DATABASE_NAME=test
DATABASE_ENABLE_SSL=true
.env.example
file to the .env
file..env
file, and replace the placeholders for <host>
, <user>
, and <password>
with the copied connection parameters.DATABASE_ENABLE_SSL
to true
to enable a TLS connection. (Required for public endpoint)DATABASE_SSL_CA
to the file path of the CA certificate provided by TiDB Cloud. (Required for public endpoint)DATABASE_HOST=<host>
DATABASE_PORT=4000
DATABASE_USER=<user>
DATABASE_PASSWORD=<password>
DATABASE_NAME=test
DATABASE_ENABLE_SSL=true
DATABASE_SSL_CA=/path/to/ca.pem
.env.example
file to the .env
file..env
file, and replace the placeholders for <host>
, <user>
, and <password>
with the copied connection parameters.The TiDB Self-Hosted cluster using non-encrypted connection between TiDB’s server and clients by default, SKIP the below steps if your cluster doesn’t enable TLS connections.
DATABASE_ENABLE_SSL
to true
to enable a TLS connection.DATABASE_SSL_CA
to the file path of the trusted CA certificate defined with ssl-ca
option.DATABASE_HOST=<host>
DATABASE_PORT=4000
DATABASE_USER=<user>
DATABASE_PASSWORD=<password>
DATABASE_NAME=test
# DATABASE_ENABLE_SSL=true
# DATABASE_SSL_CA=/path/to/ca.pem
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.
Expected execution output:
🔌 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.
The following code use the environment variables (stored in the .env
file) as the connection options to establish a database connection with the TiDB cluster:
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)
To connect TiDB Serverless with the public endpoint, please set up the environment variable DATABASE_ENABLE_SSL
to true
to enable TLS connection.
By default, the mysql2 gem will search for existing CA certificates in a particular order until a file is discovered.
While it is possible to specify the CA certificate path manually, this approach may cause significant inconvenience in multi-environment deployment scenarios, as different machines and environments may store the CA certificate in varying locations. Therefore, setting sslca
to nil
is recommended for flexibility and ease of deployment across different environments.
To connect TiDB Dedicated with the public endpoint, please set up the environment variable DATABASE_ENABLE_SSL
to true
to enable TLS connection and using DATABASE_SSL_CA
to specify the file path of CA certificate downloaded from TiDB Cloud Web Console.
The following query creates a single Player with two fields and return 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.
The following query returns a single Player
record 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.
The following query updated a single Player
record 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.
The following query deletes a single Player
record:
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.