druid.properties配置文件
# key = value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db02?rewriteBatchedStatements=true
username=root_db02
password=root_db02
# 初始连接大小
initialSize=10
# 最小空闲连接大小
minIdle=5
# 最大活动连接大小
maxActive=50
# 最大等待时间(5000ms)
maxWait=5000
pom.xml|druid-jar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>
DruidUtils类
package com.data_source.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DruidUtils {
private static final DataSource dataSource;
static {
try {
Properties properties = new Properties();
properties.load(new FileReader("G:\\Xx-hH\\TechnicalArea\\WebBackEnd\\Java\\JavaSE\\Phase_II\\chapter25\\src\\druid.properties"));
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
@SuppressWarnings("DuplicatedCode")
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
DruidUtilsUse类
package com.data_source.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DruidUtilsUse {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String selectSql = "select * from admin where name = ?";
try {
connection = DruidUtils.getConnection();
preparedStatement = connection.prepareStatement(selectSql);
preparedStatement.setString(1, "fx");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String name = resultSet.getString("name");
String pwd = resultSet.getString("pwd");
System.out.println(name + "\t" + pwd);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DruidUtils.close(resultSet, preparedStatement, connection);
}
}
}