java如何封装JDBC工具类呢?

欣喜 Java经验 发布时间:2025-02-24 09:01:22 阅读数:3972 1
下文笔者讲述JDBC工具类的简介说明,如下所示
我们只需编写一个DbUtil工具类
    即可在后续中使用
例:JDBC工具类
public class DBUtil {
	//静态变量:在类加载时候执行,并且是有先后顺序的.自上而下
	private static ResourceBundle bundle=ResourceBundle.getBundle("resource1.jdbc");
	private static String driver=bundle.getString("driver");
	private static String url=bundle.getString("url");
	private static String username=bundle.getString("username");
	private static String password=bundle.getString("password");
 
	static{
		//注册驱动(注册却动只需要注册一次,放在静态代码块当中.DBUtil类加载的时候执行)
	   try {
			//"com.mysql.jdbc.Driver"是连接数据库的驱动,不能写死,因为可能以后改成Oracle数据库
			//如果连接Oracle数据库的时候,还需要修改java代码,显然违背OCP开闭原则
			//OCP开闭原则:对扩展开发,对修改关闭.(什么是复合OCP呢?在进行功能扩展的时候,不需要修改java源代码)
			//Class.forName("com.mysql.cj.jdbc.Driver");
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
 
	//获取数据库连接对象  抛异常,谁使用,谁负责
	public static Connection getConnection() throws SQLException {
		Connection connection = DriverManager.getConnection(url, username, password);
		return connection;
	}
 
	//关闭连接 释放资源
 
	/**
	 * 释放资源
	 * @param conn 数据库连接对象
	 * @param st 执行对象
	 * @param rs 结果集对象
	 */
	public static void close(Connection conn,Statement st,ResultSet rs){
 
		if (conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (st!=null){
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

工具类使用代码

Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;

int count=0;
try {
    conn = DBUtil.getConnection();
    //是否开启事务(关闭自动提交)  看具体情况
    conn.setAutoCommit(false);
    
    conn.commit();
} catch (SQLException e) {
    //回滚
    if(conn!=null){
        try {
            conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    e.printStackTrace();
}finally {
    //释放资源
    DBUtil.close(conn, ps, null);
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202502/17403589068319.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者