package druidJDBCUtils;
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 DruidJDBCUtils {
//定义成员变量
private static DataSource ds;
//静态代码块加载配置文件
static {
try {
Properties prop = new Properties();
InputStream is = DruidJDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
prop.load(is);
ds = DruidDataSourceFactory.createDataSource(prop);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 获取连接池方法
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 关闭资源方法
* close()查询sql方法
*/
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();
}
}
}
/**
* 关闭资源方法
* close()增删改sql方法
*/
public static void close(Statement statement, Connection connection) {
close(null, statement, connection);
}
}
2022-03-03 18:55:08
2KB
Druid
1