黑马程序员
数据库连接池–druid–工具类
- JDBCUtils_druid
package cn.itcast.dataSource.utils;
import cn.itcast.dataSource.druid.Druid_Demo1;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils_druid {
static DataSource dataSource=null;
static {
try {
Properties properties = new Properties();
ClassLoader classLoader = Druid_Demo1.class.getClassLoader();
InputStream resourceAsStream = classLoader.getResourceAsStream("druid.properties");
properties.load(resourceAsStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConn() throws SQLException {
Connection connection = dataSource.getConnection();
return connection;
}
public static DataSource getDataSource(){
return dataSource;
}
public static void close(Connection connection, Statement statement){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection connection, Statement statement, ResultSet resultSet){
close(connection,statement);
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}