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
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
On this page
Help Center/ Distributed Database Middleware/ Best Practices/ Accessing DDM Using a JDBC Connection Pool

Accessing DDM Using a JDBC Connection Pool

Updated on 2022-08-01 GMT+08:00

Scenario

When a connection pool is used, the system stores database connections in memory during initialization. Then, when you send a request to access a database, the system directly selects an available connection in the connection pool. If the connection is not required, the system returns the connection to the pool for another request to access. Connection establishment and disconnection are both managed by the connection pool itself. In addition, you can set connection pool parameters to control the number of initial connections in the connection pool, upper and lower limits of connections, maximum number of times that each connection can be used, and maximum idle time for each connection. If you prefer, you can also use your own system to monitor the number and usage of database connections.

This section describes how to access DDM using the JDBC connection pool to perform data operations. For Java programs, HikariCP is recommended.
  • Java 8: Version 3.3.1 is recommended.
  • Java 7: Version 2.4.13 is recommended.
  • Parameter useCursorFetch cannot be enabled when you connect to a DDM instance using a JDBC connection.

Procedure

  1. Configure Maven.

    • Java 8
      <dependency>
          <groupId>com.zaxxer</groupId>
          <artifactId>HikariCP</artifactId>
          <version>3.3.1</version>
      </dependency>
    • Java 7
      <dependency>
          <groupId>com.zaxxer</groupId>
          <artifactId>HikariCP-java7</artifactId>
          <version>2.4.13</version>
      </dependency>

  2. Create a table.

    Table 1 Parameters for creating a table

    Table Name

    Field

    Type

    Primary Key

    account

    account_number

    bigint

    Yes

    account_type

    varchar (45)

    No

    account_name

    varchar (50)

    No

  3. Connect to a DDM instance.

    1. Set the number of connections by configuring parameters in the JDBC URL and HikariCP parameters.
    2. Insert a data record.
    Example:
    package com.huawei.ddm.examples; 
    import java.sql.Connection; 
    import java.sql.PreparedStatement; 
    import java.sql.ResultSet; 
    import java.sql.SQLException; 
    import javax.sql.DataSource; 
    import com.zaxxer.hikari.HikariConfig; 
    import com.zaxxer.hikari.HikariDataSource; 
    
    public class HikariCPDemo { 
        private static DataSource datasource; 
        private static DataSource getDataSource() { 
            if (datasource == null) { 
                HikariConfig config = new HikariConfig(); 
                
                // Configure parameters in the JDBC URL:
                config.setJdbcUrl("jdbc:mysql:loadbalance://192.168.0.10:5066,192.168.0.11:5066/db_name?loadBalanceAutoCommitStatementThreshold=5&loadBalanceHostRemovalGracePeriod=15000&loadBalanceBlacklistTimeout=60000&loadBalancePingTimeout=5000&retriesAllDown=10&connectTimeout=10000"); 
                /* 
                // Or configure parameters in the JDBC URL as follows:
                config.addDataSourceProperty("loadBalanceAutoCommitStatementThreshold",5); 
                config.addDataSourceProperty("loadBalanceHostRemovalGracePeriod", 15000); 
                config.addDataSourceProperty("loadBalanceBlacklistTimeout", 60000); 
                config.addDataSourceProperty("loadBalancePingTimeout", 5000); 
                config.addDataSourceProperty("retriesAllDown", 10); 
                config.addDataSourceProperty("connectTimeout", 10000); 
                */ 
                config.setUsername("username"); 
                config.setPassword("password"); 
                config.setMaximumPoolSize(10); 
                config.setAutoCommit(true); 
    
                // Configure HikariCP parameters.
                config.addDataSourceProperty("cachePrepStmts", true); 
                config.addDataSourceProperty("prepStmtCacheSize", 250); 
                config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048); 
                config.addDataSourceProperty("minimumIdle", 5); 
                config.addDataSourceProperty("maximumPoolSize", 10); 
                config.addDataSourceProperty("idleTimeout", 30000); 
    
                datasource = new HikariDataSource(config); 
            } 
            return datasource; 
        } 
    
        public static void main(String[] args) { 
            Connection connection = null; 
            PreparedStatement pstmt = null; 
            ResultSet resultSet = null; 
            try { 
                DataSource dataSource = getDataSource(); 
                connection = dataSource.getConnection(); 
                System.out.println("The Connection Object is of Class: " + connection.getClass()); 
                // Start a transaction.
                connection.setAutoCommit(false);
    
                // Insert test data.
                String insertSql = "insert into account(account_number, account_type, account_name) values(?, ?, ?);";
                PreparedStatement insertStmt = connection.prepareStatement(insertSql);
                insertStmt.setLong (1, 1L); 
                insertStmt.setString (2, "manager"); 
                insertStmt.setString (3, "demotest01"); 
                insertStmt.executeUpdate(); 
                connection.commit ();
    
                // Query data.
                pstmt = connection.prepareStatement("SELECT * FROM account"); 
                resultSet = pstmt.executeQuery(); 
                while (resultSet.next()) { 
                    String accountNumber = resultSet.getString("account_number"); 
                    String accountType = resultSet.getString("account_type"); 
                    String accountName = resultSet.getString("account_name"); 
                    System.out.println(accountNumber + "," + accountType + "," + accountName); 
                } 
            } catch (Exception e) { 
                try { 
                    if (null != connection) { 
                        connection.rollback(); 
                    } 
                } catch (SQLException e1) { 
                    e1.printStackTrace(); 
                } 
                e.printStackTrace(); 
            } 
        } 
    }

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