jdbc的封装


最近上课老师讲到一套jdbc的封装,觉得很好,收藏起来

 
 
 
 
public interface IDao<T> {
   void add(T t) throws SQLException;

   void delete(Object id) throws SQLException;

   void update(T t) throws SQLException;

   List<T> queryAll() throws SQLException;

   T queryById(Object id) throws SQLException;

   T queryByName(Object name) throws SQLException;


   List<T> queryByCondition(int type, Object... objects) throws SQLException;


}
 
 

以上是dao层的封装

一下是dao的实现

public class PetDaoImpl implements IDao<Pet> {
   DBHelper<Pet> db = new DBHelper<>();
   String sql;
   Pet pet = new Pet();
   @Override
   public void add(Pet t) throws SQLException {
      sql = "insert into pet(id,name,type_name,health,love,birthday) value" +
            "(?,?,?,?,?,?)";
      //添加的时候这里没有添加雇主和卖家的信息,容易报空指针异常
      db.executeSql(DBUtil.getConnection(),sql,t.getId(),t.getName(),t.getType_name(),
            t.getHealth(),t.getLove(),t.getBirthday());
   }

   @Override
   public void delete(Object id) throws SQLException {
      sql = "delete from pet where id=?";
      db.executeSql(DBUtil.getConnection(), sql, id);

   }

   @Override
   public void update(Pet t) throws SQLException {
      sql = "update pet set name = ?,love = ? ,owner_id=?,store_id=?,type_name=?,health=?,birthday=?,where id=?";
      db.executeSql(DBUtil.getConnection(), sql, t.getName(),t.getLove(),t.getOwner_id(),t.getPetStore_id(),t.getType_name(),t.getHealth(),t.getBirthday(),t.getId());
   }

   @Override
   public List queryAll() throws SQLException {
      List<Pet> list = db.executeQuery(DBUtil.getConnection(), "select * from pet", new PetMapper());
      return list;
   }

   @Override
   public Pet queryById(Object id) throws SQLException {
      sql = "select * from pet where id=?";
      List<Pet> list = db.executeQuery(DBUtil.getConnection(), sql, new PetMapper(),id);
      pet = list.get(0);
//    System.out.println(pet.getName());
      return pet;

   }

   @Override
   public Pet queryByName(Object name) throws SQLException {
      return null;
   }

   @Override
   public List queryByCondition(int type, Object... objects) throws SQLException {
      return null;
   }
}


public interface IMapper<T> {
   T mapper(ResultSet rs) throws SQLException;

}
public class PetMapper implements IMapper<Pet> {
   

   @Override
   public Pet mapper(ResultSet rs) throws SQLException {
      Pet pet = new Pet();
      pet.setId(rs.getInt("id"));
      
      pet.setName(rs.getString("name"));//以String的形式获取结果集当前行指定列号的值
      pet.setType_name(rs.getString("type_name"));
      pet.setHealth(rs.getInt("health"));
      pet.setLove(rs.getInt("love"));
      pet.setBirthday(rs.getString("birthday"));
      return pet;//
   }
}
一下是一些执行语句的封装

public class DBHelper<T> {
   PreparedStatement ppst = null;
   ResultSet rs = null;
   List<T> list = null;

   /**
    *执行executeQuery语句,将对象存储到list里面去
    * @param conn
    * @param sql
    * @param m
    * @return
    * @throws SQLException
    */
   public List<T> executeQuery(Connection conn, String sql, IMapper<T> m, Object...objects) throws SQLException {
      ppst = conn.prepareStatement(sql);
      this.setParam(objects);
      rs = ppst.executeQuery();
      list = new ArrayList<>();
      while (rs.next()) {
         T t = m.mapper(rs);//泛型封装
         list.add(t);
      }
      DBUtil.closeAll(conn, ppst, rs);
      return list;
   }


   /**
    *
    *
    * @param conn
    * @param sql
    * @param objects
    * @throws SQLException
    */
   public void executeSql(Connection conn, String sql, Object... objects) throws SQLException {
      ppst = conn.prepareStatement(sql);
      this.setParam(objects);
      ppst.execute();
      DBUtil.closeAll(conn, ppst);
   }

   /**
    *
    *
    * @param objects
    * @throws SQLException
    */
   public void setParam(Object... objects) throws SQLException {
      if (objects != null && objects.length > 0) {
         for (int i = 0; i < objects.length; i++) {
            ppst.setObject(i + 1, objects[i]);
         }
      }
   }
}
 
 

获取连接driver和关闭jdbc的封装

    public class DBUtil {

      static Connection conn = null;

      //
      public static Connection getConnection() throws SQLException {
         //
         if (conn != null && !conn.isClosed()) {
            return conn;
         }
         try {
            Class.forName(ReadProperties.getValue("driver"));
         } catch (ClassNotFoundException e) {
            e.printStackTrace();
         }
         try {
            conn = DriverManager.getConnection(ReadProperties.getValue("url"), ReadProperties.getValue("user"),
                  ReadProperties.getValue("password"));
         } catch (SQLException e) {
            e.printStackTrace();
         }
         return conn;
      }

      //
      public static void closeAll(Connection conn, PreparedStatement ppst, ResultSet rs) {
         try {
            if (rs != null) {
               rs.close();
            }
            if (ppst != null) {
               ppst.close();
            }
            if (conn != null) {
               conn.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }

      public static void closeAll(Connection conn, PreparedStatement ppst) {
         try {
            if (ppst != null) {
               ppst.close();
            }
            if (conn != null) {
               conn.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }
}

读取配置未见的封装

public class ReadProperties {
   public static String getValue(String key){//获取配置文件中的之
      Properties prop = new Properties();
      try {
         prop.load(ReadProperties.class.getResourceAsStream("/db.properties"));
         String str = prop.getProperty(key);
         return str;
      } catch (IOException e) {
         e.printStackTrace();
      }
      return null;
   }

}
自己再创建实体类,这个封装就可以用了,


猜你喜欢

转载自blog.csdn.net/weixin_41650839/article/details/80237998
今日推荐