为下面代码添加注释 public class JdbcUtils { static LinkedList<Connection> pool=new LinkedList<>(); static { Properties properties=new Properties(); try { properties.load(new FileReader("db.properties")); } catch (IOException e) { e.printStackTrace(); } String num_ = (String) properties.get("init"); int num=Integer.parseInt(num_); for (int i = 0; i <num ; i++) { Connection connection=null; try { Class.forName((String) properties.get("driverName")); connection = DriverManager.getConnection((String) properties.get("url"), (String) properties.get("user"),(String) properties.get("pwd")); pool.add(connection); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } } public static Connection getConn(){ return pool.removeLast(); } public static void back(Connection connection){ pool.addFirst(connection); } }
时间: 2024-02-15 20:27:00 浏览: 56
/**
* JdbcUtils工具类实现数据库连接池
*/
public class JdbcUtils {
// 创建一个LinkedList对象作为连接池
static LinkedList<Connection> pool=new LinkedList<>();
// 静态代码块,当类被加载时就会执行,用于初始化连接池
static {
// 创建Properties对象,并读取db.properties配置文件
Properties properties=new Properties();
try {
properties.load(new FileReader("db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
// 获取配置文件中的连接数
String num_ = (String) properties.get("init");
int num=Integer.parseInt(num_);
// 根据连接数循环创建Connection对象,并加入连接池
for (int i = 0; i <num ; i++) {
Connection connection=null;
try {
// 加载数据库驱动
Class.forName((String) properties.get("driverName"));
// 获取数据库连接
connection = DriverManager.getConnection((String) properties.get("url"), (String) properties.get("user"),(String) properties.get("pwd"));
// 将连接加入连接池
pool.add(connection);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
/**
* 获取连接,从连接池中移除最后一个连接
* @return Connection对象
*/
public static Connection getConn(){
return pool.removeLast();
}
/**
* 将连接归还到连接池中,添加到最前面
* @param connection Connection对象
*/
public static void back(Connection connection){
pool.addFirst(connection);
}
}
阅读全文