JDBC: 创建一个JDBC工具类

什么时候自己创建工具类?

  • 如果一个功能经常要用到,我们建议把这个功能做成一个工具类,可以在不同的地方重用。 
  • “获得数据库连接”操作,将在以后的增删改查所有功能中都存在,可以封装工具类JDBCUtils。提供获取 连接对象的方法,从而达到代码的重复利用。 

 

工具类包含的内容 

  1) 可以把几个字符串定义成常量:用户名,密码,URL,驱动类 

  2) 得到数据库的连接:getConnection() 

  3) 关闭所有打开的资源

 

代码示例

 /** * JDBC 工具类 */ 

public class JDBCUtils {
    
    //1. 定义字符串常量, 记录获取连接所需要的信息 
     public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
     public static final String URL = "jdbc:mysql://localhost:3306/db4?characterEncoding=UTF-8";
     public static final String USER = "root";
     public static final String PASSWORD = "123456";

    //2. 静态代码块, 随着类的加载而加载
    static{
       try { 
           //注册驱动
            Class.forName(DRIVERNAME);
       } catch (ClassNotFoundException e) { 
             e.printStackTrace();
       }
    }

    //3. 获取连接的静态方法
    public static Connection getConnection(){
        try{
              // 获取连接对象
              Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);

              // 返回连接对象
              return connection;
        }    catch (SQLException e) {
                  e.printStackTrace();
                  return null;
        }
    }

     // 4. 关闭资源的静态方法(1)
     public static void close(Connection con, Statement st){
         if(con != null && st != null){
                try {
                         st.close();
                       con.close();
                }  catch (SQLException e) {
                        e.printStackTrace();
                } 
          }
      }

      // 4. 关闭资源的静态方法(2)
      public static void close(Connection con, Statement st, ResultSet rs){
            if(rs != null){
                 try { 
                            rs.close();
                 } catch (SQLException e) {                
                            e.printStackTrace();
                 }
            }
 
            close(con,st);
        } 
}

 

posted @ 2021-07-22 13:22  Jasper2003  阅读(84)  评论(0编辑  收藏  举报