Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ TaurusDB/ User Guide/ Connecting to a DB Instance/ Connecting to a DB Instance Through JDBC

Connecting to a DB Instance Through JDBC

Updated on 2025-02-12 GMT+08:00

Although the SSL certificate is optional if you choose to connect to a database through Java database connectivity (JDBC), you are advised to download the SSL certificate to encrypt the connections for security purposes. By default, SSL is enabled for new TaurusDB instances. SSL encrypts connections to instances but prolongs connection response time and increases CPU usage. Before enabling SSL, evaluate the impact on service performance. For details about how to enable or disable SSL, see Configuring SSL.

Prerequisites

Familiarize yourself with:

  • Computer basics
  • Java programming language
  • JDBC knowledge

Connection with the SSL Certificate

The SSL certificate needs to be downloaded and verified for connecting to databases.

NOTE:

If the ssl_type value of a database user is x509, this method is unavailable.

To check the ssl_type value of the current user, run the following command:

select ssl_type from mysql.user where user = 'xxx';

  1. Download the CA certificate or certificate bundle.

    1. On the Instances page, click the instance name to go to the Basic Information page.
    2. Click Download under SSL.

  2. Use keytool to generate a truststore file using the CA certificate.

    <keytool installation path> ./keytool.exe -importcert -alias <MySQLCACert> -­file <ca.pem> -keystore <truststore_file> -storepass <password>
    Table 1 Parameter description

    Parameter

    Description

    <keytool installation path>

    Bin directory in the JDK or JRE installation path, for example, C:\Program Files (x86)\Java\jdk­11.0.7\bin.

    <MySQLCACert>

    Name of the truststore file. Set it to a name specific to the service for future identification.

    <ca.pem>

    Name of the CA certificate downloaded and decompressed in 1, for example, ca.pem.

    <truststore_file>

    Path for storing the truststore file.

    <password>

    Password of the truststore file.

    Code example (using keytool in the JDK installation path to generate the truststore file):

    Owner:  CN=MySQL_Server_8.0.22_Auto_Generated_CA_Certificate
    Issuer: CN=MySQL_Server_8.0.22_Auto_Generated_CA_Certificate 
    Serial number: 1
    Valid from: Thu Feb 16 11:42:43 EST 2017 until: Sun Feb 14 11:42:43 EST 2027 
    Certificate fingerprints:
         MD5: 18:87:97:37:EA:CB:0B:5A:24:AB:27:76:45:A4:78:C1
         SHA1: 2B:0D:D9:69:2C:99:BF:1E:2A:25:4E:8D:2D:38:B8:70:66:47:FA:ED 
         SHA256:C3:29:67:1B:E5:37:06:F7:A9:93:DF:C7:B3:27:5E:09:C7:FD:EE:2D:18:86:F4:9C:40:D8:26:CB:DA:95: A0:24
         Signature algorithm name: SHA256withRSA Subject Public Key Algorithm: 2048-bit RSA key 
         Version: 1
         Trust this certificate? [no]: y
         Certificate was added to keystore

  3. Connect to your TaurusDB instance through JDBC.

    jdbc:mysql://<instance_ip>:<instance_port>/<database_name>? 
    requireSSL=<value1>&useSSL=<value2>&verifyServerCertificate=<value3>&trustCertificateKeyStoreUrl=file: 
    <truststore_file>&trustCertificateKeyStorePassword=<password>
    Table 2 Parameter description

    Parameter

    Description

    <instance_ip>

    IP address of the DB instance.

    NOTE:
    • If you are accessing the instance through ECS, <instance_ip> is the private IP address of the instance. You can view the private IP address in the Network Information area on the Basic Information page.
    • If you are accessing the instance through a public network, <instance_ip> is the EIP that has been bound to the instance. You can view the EIP in the Network Information area on the Basic Information page.
    • If you are accessing the instance through a proxy instance, <instance_ip> is the proxy address. You can view the proxy address on the Database Proxy page.

    <instance_port>

    Database port of the DB instance. The default port is 3306.

    NOTE:

    You can view the database port in the Network Information area on the Basic Information page.

    <database_name>

    Database name used for connecting to the instance. The default value is mysql.

    <value1>

    Value of requireSSL, indicating whether the server supports SSL. It can be either of the following:

    • true: The server supports SSL.
    • false: The server does not support SSL.
    NOTE:

    For details about the relationship between requireSSL and sslmode, see Table 3.

    <value2>

    Value of useSSL, indicating whether the client uses SSL to connect to the server. It can be either of the following:

    • true: The client uses SSL to connect to the server.
    • false: The client does not use SSL to connect to the server.
      NOTE:

      For details about the relationship between useSSL and sslmode, see Table 3.

    <value3>

    Value of verifyServerCertificate, indicating whether the client verifies the server certificate. It can be either of the following:

    • true: The client verifies the server certificate.
    • false: The client does not verify the server certificate.
      NOTE:

      For details about the relationship between verifyServerCertificate and sslmode, see Table 3.

    <truststore_file>

    Path for storing the truststore file configured in 2.

    <password>

    Password of the truststore file configured in 2.

    Table 3 Relationship between connection parameters and sslmode

    useSSL

    requireSSL

    verifyServerCertificate

    sslMode

    false

    N/A

    N/A

    DISABLED

    true

    false

    false

    PREFERRED

    true

    true

    false

    REQUIRED

    true

    N/A

    true

    VERIFY_CA

    Code example (Java code for connecting to a TaurusDB instance):

    import java.sql.Connection; 
    import java.sql.DriverManager; 
    import java.sql.ResultSet; 
    import java.sql.Statement;
    import java.sql.SQLException; 
     
    public class JDBCTest { 
        
      //There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables.
      //In this example, the username and password are stored in the environment variables. Before running the code, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed.
        static final String USER = System.getenv("EXAMPLE_USERNAME_ENV"); 
        static final String PASS = System.getenv("EXAMPLE_PASSWORD_ENV");
    
        public static void main(String[] args) {
            Connection conn = null; 
            Statement stmt = null;
    
            String url = "jdbc:mysql://<instance_ip>:<instance_port>/<database_name>?
    requireSSL=true&useSSL=true&verifyServerCertificate=true&trustCertificateKeyStoreUrl=file:
    <truststore_file>&trustCertificateKeyStorePassword=<password>";
     
            try { 
                Class.forName("com.mysql.cj.jdbc.Driver");
                conn = DriverManager.getConnection(url, USER, PASS);
     
                stmt = conn.createStatement(); 
                String sql = "show status like 'ssl%'";
                ResultSet rs = stmt.executeQuery(sql); 
    
                int columns = rs.getMetaData().getColumnCount();
                for (int i = 1; i <= columns; i++) {
                    System.out.print(rs.getMetaData().getColumnName(i));
                    System.out.print("\t");
                }
    
                while (rs.next()) { 
                    System.out.println(); 
                    for (int i = 1; i <= columns; i++) {
                        System.out.print(rs.getObject(i));
                        System.out.print("\t");
                    } 
                }
                rs.close(); 
                stmt.close(); 
                conn.close(); 
            } catch (SQLException se) { 
                se.printStackTrace(); 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } finally { 
                // release resource .... 
            } 
        } 
    }

Connection Without the SSL Certificate

NOTE:

You do not need to download the SSL certificate because certificate verification on the server is not required.

  1. Connect to your TaurusDB instance through JDBC.

    jdbc:mysql://<instance_ip>:<instance_port>/<database_name>?useSSL=false
    Table 4 Parameter description

    Parameter

    Description

    <instance_ip>

    IP address of the DB instance.

    NOTE:
    • If you are accessing the instance through ECS, <instance_ip> is the private IP address of the instance. You can view the private IP address in the Network Information area on the Basic Information page.
    • If you are accessing the instance through a public network, <instance_ip> is the EIP that has been bound to the instance. You can view the EIP in the Network Information area on the Basic Information page.

    <instance_port>

    Database port of the DB instance. The default port is 3306.

    NOTE:

    You can view the database port in the Network Information area on the Basic Information page.

    <database_name>

    Database name used for connecting to the instance. The default value is mysql.

    Code example (Java code for connecting to a TaurusDB instance):
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class MyConnTest {
    	final public static void main(String[] args) {
    		Connection conn = null;
    		// set sslmode here.
    		// no ssl certificate, so do not specify path.
    		String url = "jdbc:mysql://192.168.0.225:3306/my_db_test?useSSL=false";
    		try {
    			Class.forName("com.mysql.jdbc.Driver");
                            //There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables.
                            //In this example, the username and password are stored in the environment variables. Before running the code, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed.
                            conn = DriverManager.getConnection(url, System.getenv("EXAMPLE_USERNAME_ENV"), System.getenv("EXAMPLE_PASSWORD_ENV"));
    			System.out.println("Database connected");
    
    			Statement stmt = conn.createStatement();
    			ResultSet rs = stmt.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
    			while (rs.next()) {
    				System.out.println(rs.getString(1));
    			}
    			rs.close();
    			stmt.close();
    			conn.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    			System.out.println("Test failed");
    		} finally {
    			// release resource ....
    		}
    	}
    }

Related Issues

  • Symptom

    When you use JDK 8.0 or a later version to connect to your TaurusDB instance with an SSL certificate downloaded, an error similar to the following is reported:

    javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or
    cipher suites are inappropriate)
        at sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:171) ~[na:1.8.0_292]
        at sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:98) ~
    [na:1.8.0_292]
        at sun.security.ssl.TransportContext.kickstart(TransportContext.java:220) ~
    [na:1.8.0_292]
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:428) ~
    [na:1.8.0_292]
        at
    com.mysql.cj.protocol.ExportControlled.performTlsHandshake(ExportControlled.java:316) ~
    [mysql-connector-java-8.0.17.jar:8.0.17]
        at
    com.mysql.cj.protocol.StandardSocketFactory.performTlsHandshake(StandardSocketFactory.java
    :188) ~[mysql-connector-java8.0.17.jar:8.0.17]
        at
    com.mysql.cj.protocol.a.NativeSocketConnection.performTlsHandshake(NativeSocketConnection.
    java:99) ~[mysql-connector-java8.0.17.jar:8.0.17]
        at
    com.mysql.cj.protocol.a.NativeProtocol.negotiateSSLConnection(NativeProtocol.java:331) ~
    [mysql-connector-java8.0.17.jar:8.0.17]
    ... 68 common frames omitted
  • Solution

    Specify the corresponding parameter values in the code link of 3 based on the JAR package used by the client. Example:

    • mysql-connector-java-5.1.xx.jar (For 8.0.18 and earlier versions, use the enabledTLSProtocols parameter. For details, see Connecting Securely Using SSL.)
      jdbc:mysql://<instance_ip>:<instance_port>/<database_name>? 
       requireSSL=true&useSSL=true&verifyServerCertificate=true&trustCertificateKeyStoreUrl=file: 
       <truststore_file>&trustCertificateKeyStorePassword=<password>& enabledTLSProtocols=TLSv1.2
    • mysql-connector-java-8.0. xx.jar (For connection drivers later than 8.0.18, use the tlsVersions parameter.)
      jdbc:mysql://<instance_ip>:<instance_port>/<database_name>? 
       requireSSL=true&useSSL=true&verifyServerCertificate=true&trustCertificateKeyStoreUrl=file: 
       <truststore_file>&trustCertificateKeyStorePassword=<password>& tlsVersions =TLSv1.2

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback