数据库连接池Druid使用方法
一、Druid连接池使用代码示例
import com.alibaba.druid.pool.DruidAbstractDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class DruidTest {
@Test
public void test1() throws SQLException {
DruidAbstractDataSource dds = new DruidDataSource();
dds.setDriverClassName("com.mysql.cj.jdbc.Driver");
dds.setUrl("jdbc:mysql://10.10.128.100:3306/dw?useUnicode=true&characterEncoding=utf-8");
dds.setUsername("root");
dds.setPassword("nio123456!A");
dds.setInitialSize(10);
dds.setMaxActive(20);
Connection conn = dds.getConnection();
System.out.println(conn); //com.mysql.cj.jdbc.ConnectionImpl@10959ece
}
@Test
public void test2() throws Exception {
Properties props = new Properties();
props.load(this.getClass().getClassLoader().getResourceAsStream("druid.properties"));
DataSource ds = DruidDataSourceFactory.createDataSource(props);
Connection conn = ds.getConnection();
System.out.println(conn); //com.mysql.cj.jdbc.ConnectionImpl@59af0466
}
}
二、druid.properties设置数据库连接信息
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://10.10.128.100:3306/dw?useUnicode=true&characterEncoding=utf-8
username: root
password: nio123456!A
initialSize: 10
maxActive: 20