Druid连接池 dbutils包

Druid连接池

package com.JDBC;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;


//Druid获取连接
public class DruidTest {
    private static DataSource dataSource;
    static{
        try {
            InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws Exception {
        Connection connection = dataSource.getConnection();
        return connection;
    }
}

/* druid.properties
url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf-8&useSSL=true
username=root
password=123456
driverClassName=com.mysql.cj.jdbc.Driver
*/

dbutils:(数据库操作工具类)

package com;

import com.JDBC.DruidTest;
import com.JDBC.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import java.sql.Connection;

public class QueryRunnerTest {
    @Test
    public  void insertTest(){
        Connection connection = null;
        try {
            QueryRunner queryRunner = new QueryRunner();
            connection = DruidTest.getConnection();
            String sql = "insert into pet(name,age) values(?,?);";
            queryRunner.update(connection, sql, "Jie",5);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            JDBCUtils.closeConnection(connection, null);
        }
    }
  
@Test
public void queryTest() {
List<Pet> query = null;
Connection connection = null;
try {
QueryRunner queryRunner = new QueryRunner();
connection = DruidTest.getConnection();
String sql = "select * from pet where age<?";
BeanListHandler<Pet> petBeanHandler = new BeanListHandler<>(Pet.class);
query = queryRunner.query(connection, sql, petBeanHandler, 6);
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeConnection(connection, null);
}
query.forEach(System.out::println);
}
}

 

Druid连接池 dbutils包

上一篇:jmeter-08(实现连接数据库操作)


下一篇:NodeJs + Mysql 实现项目开发