package cn.tedu.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;
/**
* 封装数据库连接
* @author DELL
*
*/
public class DBUtil {
private static BasicDataSource ds;
static {
try {
//利用properties文件初始化数据库连接池
Properties cfg = new Properties();
InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
cfg.load(in);
String driver = cfg.getProperty("driver");
String url = cfg.getProperty("url");
String username = cfg.getProperty("username");
String password = cfg.getProperty("password");
ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//连接数据库
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//关闭数据库连接
public static void close(Connection conn) {
try {
if(conn!=null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
DBUtil——封装数据库连接
最新推荐文章于 2024-05-02 12:00:00 发布