Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

TiDB Basics

1. Introduction

TiDB is an open-source distributed NewSQL database that provides high availability, horizontal scalability, and strong consistency. It is designed to support OLTP (Online Transaction Processing) workloads and is compatible with the MySQL protocol.

2. Key Concepts

2.1 Distributed Architecture

TiDB features a distributed architecture composed of three main components:

  • **TiDB Server**: The SQL layer that handles SQL parsing and execution.
  • **TiKV**: A distributed transactional key-value storage engine.
  • **PD (Placement Driver)**: Responsible for cluster management and metadata storage.

2.2 Horizontal Scalability

TiDB can scale horizontally by adding more TiDB and TiKV nodes, allowing it to handle increased loads without downtime.

2.3 Strong Consistency

It uses the Raft consensus algorithm to ensure strong consistency, meaning that data written to the database is always readable in a consistent state.

3. Installation

To install TiDB, follow these steps:

  1. Download the latest release from the official website.
  2. Unzip the package and navigate to the directory.
  3. Start the TiDB server using the command:
  4. ./bin/tidb-server
  5. Start TiKV and PD servers to complete the setup.

4. Basic Usage

Once TiDB is running, you can connect to it using MySQL clients. Here’s how to create a new database and table:

mysql -h 127.0.0.1 -P 4000 -u root -p
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100),
    email VARCHAR(100)
);

You can then insert data as follows:

INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');

5. Best Practices

5.1 Use Prepared Statements

Always use prepared statements to enhance security and performance.

5.2 Monitor Performance

Utilize monitoring tools provided by TiDB to observe performance metrics and adjust the configuration as necessary.

5.3 Regular Backups

Set up regular backups to prevent data loss. Use tools like br (Backup & Restore) to create backups.

6. FAQ

What is TiDB?

TiDB is a distributed NewSQL database that supports horizontal scalability and strong consistency.

Is TiDB compatible with MySQL?

Yes, TiDB is compatible with the MySQL protocol, allowing MySQL clients to connect and interact with it.

Can TiDB scale horizontally?

Yes, TiDB can scale horizontally by adding more nodes to the cluster.