〖代码〗JDBCUtils使用druid数据库连接池工具类
package utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static DataSource ds; // 数据源
/*
* 读取JDBC配置文件(写在静态代码块中,这样读取只进行一次)
*/
static {
// 1.创建Properties集合类
Properties pro = new Properties();
try {
// 2.通过反射机制读取配置文件
pro.load(JdbcUtils.class.getClassLoader().getResourceAsStream("properties/druid.properties"));
// 3.获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 获取连接池
*/
public static DataSource getDataSource() throws SQLException {
return ds;
}
/*
* 获取连接
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/*
* 关闭连接
*/
public static void close(ResultSet rs, PreparedStatement pst, Connection con) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
我寻见一片海 碧蓝且耀着光
大片船只航行其上 都向着远方
Shared by Foriver_江河