数据库连接池工具类
程序员文章站
2022-05-18 17:44:33
package model.dao;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import java.io.IOException;import java.io.InputStream;import java.sql.*;import java.util.Properties;public class BaseDao { private static Stri...
package model.dao;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
private static DataSource dataSource;
static
{
//读取资源文件,获取连接参数
Properties properties=new Properties();
//通过类加载器读取资源文件
InputStream is=BaseDao.class.getClassLoader().getResourceAsStream("druid.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
try {
dataSource= DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接池
public static DataSource getDataSource()
{
return dataSource;
}
//获取数据库连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
//释放资源
public static void close(Statement statement,Connection connection)
{
close(null,statement,connection);
}
//重载方法
public static void close(ResultSet resultSet,Statement statement, Connection connection)
{
if(resultSet!=null)
{
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null)
{
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null)
{
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
本文地址:https://blog.csdn.net/qq_44627732/article/details/109646554
上一篇: JUC—CountDownLatch闭锁源码深度解析
下一篇: premiere怎么制作星空效果?