druid.properties
driverClassName:com.mysql.jdbc.Driver
url=jdbc:mysql:(连接)?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
username=
password=
# 初始连接数
initialSize=5
# 最大连接数
maxActive=10
# 最大连接等待时间
maxWait=3000
JDBCUtils
public class JDBCUtils {
private static DataSource dataSource;
/**
*读取配置文件
*/
static {
try {
// 加载配置文件
Properties properties = new Properties();
properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
// 获取DataSource
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* 获取连接池
*/
public static DataSource getDataSource(){
return dataSource;
}
/**
* 释放资源
*/
public static void close(Statement statement, Connection connection) {
close(null, statement, connection);
}
/**
* 释放资源
*/
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}