JDBCUtils类
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
//Druid的封装工具类
public class JDBCUntils {
private static DataSource dataSource;
static {
//读取配置文件
try {
Properties properties = new Properties();
properties.load(JDBCUntils.class.getClassLoader().getResourceAsStream("druid.properties"));
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
//获取数据库连接对象
return dataSource.getConnection();
}
//返回数据库连接池对象
public static DataSource getDataSource() {
return dataSource;
}
//释放资源
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//重载个释放资源的方法
public static void close(Connection connection, Statement statement) {
close(connection,statement,null);
}
}
druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///db1
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000