Java Durid for detailed explanation of JDBC connection

  • 2021-11-13 01:46:59
  • OfStack

Directory 1. Introduction to Druid 2. Benefits of Druid 3. Connecting JDBC MySQL with Durid 3.1 Adding Druid dependencies, database drivers 3.2 Creating JDBC tool classes 3.3 Adding configuration parameters 3.4 Test code summary

1. Introduction to Druid

Druid is an open source database connection pool of Ali. As a rising star, its performance is higher than dbcp and c3p0, and it is used more and more widely.

Of course, Druid is not only a connection pool, but also many other functions.

2. Advantages of Druid

High performance. The performance is much higher than dbcp and c3p0. As long as it is the database supported by jdbc, druid supports it, and it has good support for the database. And Druid is specially optimized for oracle and mysql. Provide monitoring function. It can monitor the execution time of sql statement, the holding time of ResultSet, the number of returned rows, the number of updated rows, the number of errors, the error stack and other information to understand the connection pool and the working condition of sql statement, and facilitate statistics and analysis of the execution performance of SQL

3. Connect JDBC MySQL using Durid

3.1 Adding Druid dependencies, database-driven


<!-- mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>
<!-- druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.27</version>
</dependency>

3.2 Creating an JDBC tool class


package cn.kgc.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
 *  " JDBC "Business Tools Class 
 */
public class JDBCReadUtils implements Serializable {
    private static Logger logger = Logger.getLogger(JDBCReadUtils.class);
    /**
     *  Realization JDBCHelper Singletonization of 
     */
    private static JDBCReadUtils instance = null;
    private QueryRunner runner = null;
    /**
     *  In the process of implementing singletons, create only 1 Database connection pool of 
     */
    private JDBCReadUtils(String url) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File(url)));
            runner = new QueryRunner(DruidDataSourceFactory.createDataSource(properties));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    public JDBCReadUtils() {
    }
    /**
     *  Get singleton 
     *
     * @return  Singleton 
     */
    public static JDBCReadUtils getInstance(String url) {
        if (instance == null) {
            synchronized (JDBCReadUtils.class) {
                if (instance == null) {
                    instance = new JDBCReadUtils(url);
                }
            }
        }
        return instance;
    }
    /**
     *  Query (returns Array Results) 
     */
    private Object[] queryArray(String sql, Object... params) {
        Object[] result = null;
        try {
            result = runner.query(sql, new ArrayHandler(), params);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     *  Query (returns ArrayList Results) 
     */
    public List<Object[]> queryArrayList(String sql, Object... params) {
        List<Object[]> result = null;
        try {
            result = runner.query(sql, new ArrayListHandler(), params);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        }
        return result == null ? new ArrayList<>() : result;
    }
    /**
     *  Updates (including UPDATE , INSERT , DELETE Returns the number of rows affected) 
     */
    public int update(String sql, Object... params) {
        int result = 0;
        try {
            result = runner.update(sql, params);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        }
        return result;
    }
}

3.3 Adding Configuration Parameters

Add the jdbc. properties file to the resource directory and add the following configuration


driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://singleNode:3306/spark?useSSL=false&createDatabaseIfNotExist=true&characterEncoding=UTF-8
username=root
password=root

3.4 Test code


package cn.kgc;
import cn.kgc.utils.JDBCReadUtils;
import java.util.List;
public class Test {
    public static void main(String[] args) {
        List<Object[]> result = JDBCReadUtils.getInstance("C:\\Users\\Administrator\\Desktop\\ Headquarters Practical Combat Course \\spark\\project\\src\\main\\resources\\jdbc.properties")
                .queryArrayList("select * from entity_question_number_accuracy limit 10;");
        for (Object o[] : result) {
            System.out.println(o[0] + "\t" + o[1] + "\t" + o[2] + "\t" + o[3]);
        }
    }
}

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: