Skip to content

Latest commit

 

History

History
319 lines (220 loc) · 13.4 KB

dev-guide-sample-application-java-jdbc.md

File metadata and controls

319 lines (220 loc) · 13.4 KB
title summary aliases
Connect to TiDB with JDBC
Learn how to connect to TiDB using JDBC. This tutorial gives Java sample code snippets that work with TiDB using JDBC.
/tidb/dev/sample-application-java
/tidb/dev/dev-guide-sample-application-java

Connect to TiDB with JDBC

TiDB is a MySQL-compatible database, and JDBC (Java Database Connectivity) is the data access API for Java. MySQL Connector/J is MySQL's implementation of JDBC.

In this tutorial, you can learn how to use TiDB and JDBC to accomplish the following tasks:

  • Set up your environment.
  • Connect to your TiDB cluster using JDBC.
  • Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.

Note:

This tutorial works with TiDB Cloud Serverless, TiDB Cloud Dedicated, and TiDB Self-Managed.

Prerequisites

To complete this tutorial, you need:

  • Java Development Kit (JDK) 17 or higher. You can choose OpenJDK or Oracle JDK based on your business and personal requirements.
  • Maven 3.8 or higher.
  • Git.
  • A TiDB cluster.

If you don't have a TiDB cluster, you can create one as follows:

Note:

For security considerations, it is recommended that you use VERIFY_IDENTITY to establish TLS connections to TiDB clusters when connecting over the internet. Both TiDB Cloud Serverless and TiDB Cloud Dedicated use Subject Alternative Name (SAN) certificates, which require MySQL Connector/J version to be greater than or equal to 8.0.22.

If you don't have a TiDB cluster, you can create one as follows:

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-java-jdbc-quickstart.git
cd tidb-java-jdbc-quickstart

Step 2: Configure connection information

Connect to your TiDB cluster depending on the TiDB deployment option you've selected.

  1. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  2. Click Connect in the upper-right corner. A connection dialog is displayed.

  3. Ensure the configurations in the connection dialog match your operating environment.

    • Connection Type is set to Public
    • Branch is set to main
    • Connect With is set to General
    • Operating System matches your environment.

    Tip:

    If your program is running in Windows Subsystem for Linux (WSL), switch to the corresponding Linux distribution.

  4. Click Generate Password to create a random password.

    Tip:

    If you have created a password before, you can either use the original password or click Reset Password to generate a new one.

  5. Run the following command to copy env.sh.example and rename it to env.sh:

    cp env.sh.example env.sh
  6. Copy and paste the corresponding connection string into the env.sh file. The example result is as follows:

    export TIDB_HOST='{host}'  # e.g. gateway01.ap-northeast-1.prod.aws.tidbcloud.com
    export TIDB_PORT='4000'
    export TIDB_USER='{user}'  # e.g. xxxxxx.root
    export TIDB_PASSWORD='{password}'
    export TIDB_DB_NAME='test'
    export USE_SSL='true'

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog.

    TiDB Cloud Serverless requires a secure connection. Therefore, you need to set the value of USE_SSL to true.

  7. Save the env.sh file.

  1. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  2. Click Connect in the upper-right corner. A connection dialog is displayed.

  3. In the connection dialog, select Public from the Connection Type drop-down list, and then click CA cert to download the CA certificate.

    If you have not configured the IP access list, click Configure IP Access List or follow the steps in Configure an IP Access List to configure it before your first connection.

    In addition to the Public connection type, TiDB Dedicated supports Private Endpoint and VPC Peering connection types. For more information, see Connect to Your TiDB Dedicated Cluster.

  4. Run the following command to copy env.sh.example and rename it to env.sh:

    cp env.sh.example env.sh
  5. Copy and paste the corresponding connection string into the env.sh file. The example result is as follows:

    export TIDB_HOST='{host}'  # e.g. tidb.xxxx.clusters.tidb-cloud.com
    export TIDB_PORT='4000'
    export TIDB_USER='{user}'  # e.g. root
    export TIDB_PASSWORD='{password}'
    export TIDB_DB_NAME='test'
    export USE_SSL='false'

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog.

  6. Save the env.sh file.

  1. Run the following command to copy env.sh.example and rename it to env.sh:

    cp env.sh.example env.sh
  2. Copy and paste the corresponding connection string into the env.sh file. The example result is as follows:

    export TIDB_HOST='{host}'
    export TIDB_PORT='4000'
    export TIDB_USER='root'
    export TIDB_PASSWORD='{password}'
    export TIDB_DB_NAME='test'
    export USE_SSL='false'

    Be sure to replace the placeholders {} with the connection parameters, and set USE_SSL to false. If you are running TiDB locally, the default host address is 127.0.0.1, and the password is empty.

  3. Save the env.sh file.

Step 3: Run the code and check the result

  1. Execute the following command to run the sample code:

    make
  2. Check the Expected-Output.txt to see if the output matches.

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-java-jdbc-quickstart repository.

Connect to TiDB

public MysqlDataSource getMysqlDataSource() throws SQLException {
    MysqlDataSource mysqlDataSource = new MysqlDataSource();

    mysqlDataSource.setServerName(${tidb_host});
    mysqlDataSource.setPortNumber(${tidb_port});
    mysqlDataSource.setUser(${tidb_user});
    mysqlDataSource.setPassword(${tidb_password});
    mysqlDataSource.setDatabaseName(${tidb_db_name});
    if (${tidb_use_ssl}) {
        mysqlDataSource.setSslMode(PropertyDefinitions.SslMode.VERIFY_IDENTITY.name());
        mysqlDataSource.setEnabledTLSProtocols("TLSv1.2,TLSv1.3");
    }

    return mysqlDataSource;
}

When using this function, you need to replace ${tidb_host}, ${tidb_port}, ${tidb_user}, ${tidb_password}, and ${tidb_db_name} with the actual values of your TiDB cluster.

Insert data

public void createPlayer(PlayerBean player) throws SQLException {
    MysqlDataSource mysqlDataSource = getMysqlDataSource();
    try (Connection connection = mysqlDataSource.getConnection()) {
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO player (id, coins, goods) VALUES (?, ?, ?)");
        preparedStatement.setString(1, player.getId());
        preparedStatement.setInt(2, player.getCoins());
        preparedStatement.setInt(3, player.getGoods());

        preparedStatement.execute();
    }
}

For more information, refer to Insert data.

Query data

public void getPlayer(String id) throws SQLException {
    MysqlDataSource mysqlDataSource = getMysqlDataSourceByEnv();
    try (Connection connection = mysqlDataSource.getConnection()) {
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM player WHERE id = ?");
        preparedStatement.setString(1, id);
        preparedStatement.execute();

        ResultSet res = preparedStatement.executeQuery();
        if(res.next()) {
            PlayerBean player = new PlayerBean(res.getString("id"), res.getInt("coins"), res.getInt("goods"));
            System.out.println(player);
        }
    }
}

For more information, refer to Query data.

Update data

public void updatePlayer(String id, int amount, int price) throws SQLException {
    MysqlDataSource mysqlDataSource = getMysqlDataSourceByEnv();
    try (Connection connection = mysqlDataSource.getConnection()) {
        PreparedStatement transfer = connection.prepareStatement("UPDATE player SET goods = goods + ?, coins = coins + ? WHERE id=?");
        transfer.setInt(1, -amount);
        transfer.setInt(2, price);
        transfer.setString(3, id);
        transfer.execute();
    }
}

For more information, refer to Update data.

Delete data

public void deletePlayer(String id) throws SQLException {
    MysqlDataSource mysqlDataSource = getMysqlDataSourceByEnv();
    try (Connection connection = mysqlDataSource.getConnection()) {
        PreparedStatement deleteStatement = connection.prepareStatement("DELETE FROM player WHERE id=?");
        deleteStatement.setString(1, id);
        deleteStatement.execute();
    }
}

For more information, refer to Delete data.

Useful notes

Using driver or ORM framework?

The Java driver provides low-level access to the database, but it requires the developers to:

  • Manually establish and release database connections.
  • Manually manage database transactions.
  • Manually map data rows to data objects.

Unless you need to write complex SQL statements, it is recommended to use ORM framework for development, such as Hibernate, MyBatis, or Spring Data JPA. It can help you:

  • Reduce boilerplate code for managing connections and transactions.
  • Manipulate data with data objects instead of a number of SQL statements.

Next steps

Need help?

Ask the community on Discord or Slack, or submit a support ticket.

Ask the community on Discord or Slack, or submit a support ticket.