package cn.itcast.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class JDBCUtils {
/**
* 关闭资源:查询后关闭,增加、修改、删除后关闭
*/
public static void release(Statement stmt, Connection conn) { //<span style="color:#ff0000;">释放资源工具类 利用重载来实现释放有无ResultSet存在的资源占用</span>
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static void release(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
release(stmt, conn);
}
/**
* 建立连接
*
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws SQLException,
ClassNotFoundException { <span style="color:#ff0000;">//建立连接工具类</span>
// 加载配置文件
ResourceBundle bundle = ResourceBundle.getBundle("dbconfig");
String driverClass = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String pwd = bundle.getString("pwd");
// 加载驱动
Class.forName(driverClass);
// 建立连接
Connection conn = DriverManager.getConnection(url, user, pwd);
return conn;
}
}
建立mysql与数据库连接和释放资源 工具类
最新推荐文章于 2022-09-14 09:27:14 发布