자바 기초 개발 의 JDBC 조작 데이터베이스 첨삭 검사,페이지 별 조회 실례 상세 설명

12294 단어 JavaJDBC
데이터 베 이 스 를 조작 하 는 것 은 삭제 하고 고 치 는 것 일 뿐 입 니 다.그 중에서 조회 작업 이 가장 복잡 하기 때문에 조 회 를 따로 설명 하 겠 습 니 다.제 가 사용 하 는 Mysql 데이터 베 이 스 는...
첨삭 검사 조작
페이지 조회 조작
1.검색 결 과 를 list 로 되 돌려 줍 니 다.
2.검색 결 과 를 jsonArray 로 되 돌려 줍 니 다.
3.총 기록 항목 수 조회
우선 관련 설정 정 보 를 살 펴 보 겠 습 니 다.

public static final String USER_NAME = "root";
public static final String PWD = "123456789";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/web_demon";
/**              */
public static final int PAGE_SIZE_DEFAULT = 10;
첨삭 조작
데이터베이스 연결 대상 가 져 오기

/**
   *        
   * @return        
   */
  public Connection getConnection(Connection conn) {
    if(conn == null){
      try {
        Class.forName(Config.DRIVER);
        conn = DriverManager.getConnection(Config.URL, Config.USER_NAME, Config.PWD);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return conn;
  }
패 키 징 추가 삭제 작업

/**
   *   ,  ,    
   * @param sql    sql  
   *        :     "insert into user (name,sex) values (?,?)";
   *             "delete from user where id=?";
   *             "update user set name=?,sex=? where id=? and sex=?";
   * @param values       
   * @return     ,-1   
   */
  private int execute(String sql,Object... values){
    Connection conn = null;
    PreparedStatement pStmt = null;
    try {
      conn = this.getConnection(conn);
      pStmt = conn.prepareStatement(sql);
      //    
      if(pStmt != null && values != null && values.length > 0){
        for (int i = 0; i < values.length; i++) {
          pStmt.setObject(i+1, values[i]);
        }
      }
      int i =pStmt.executeUpdate();
      return i;
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        this.closeConnection(conn);
      }
    }
    return -1;
  }
호출 방법

//  
public static void insert(){
    String sql = "insert into user (name,sex) values (?,?)";
    Object[] values = new Object[]{"  ",0};
    int res = baseImp.execute(sql, values);
    System.out.println("insert res="+res);
  }
//  
public static void delete(){
    String sql = "delete from user where id=?";
    Object[] values = new Object[]{2};
    int res = baseImp.execute(sql, values);
    System.out.println("delete res="+res);
  }
//  
public static void update(){
    String sql = "update user set name=?,sex=? where id=? and sex=?";
    Object[] values = new Object[]{"  ",1,1,0};
    int res = baseImp.execute(sql, values);
    System.out.println("update res="+res);
  }
조회 조작
1.검색 결 과 를 list 로 되 돌려 줍 니 다.

/**
   *      list  
   * @param pageIndex   
   * @param pageSize       
   * @param attachTableName         key     ,  :user.id, id
   * @param sql        :"select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id"
   * @param values
   * @throws SQLException 
   */
  private List<Map<String, Object>> queryList(int pageIndex,int pageSize,boolean attachTableName,String sql,Object... values) throws SQLException{
    Connection conn = null;
    PreparedStatement pStmt = null;
    List<Map<String, Object>> dataList = null;
    //    
    if(pageIndex <= 0){
      pageIndex = 1;
    }
    if(pageSize <= 0){
      pageSize = Config.PAGE_SIZE_DEFAULT;
    }
    conn = this.getConnection(conn);
    pStmt = conn.prepareStatement(sql);
    //    
    if(pStmt != null && values != null && values.length > 0){
      for (int i = 0; i < values.length; i++) {
        pStmt.setObject(i+1, values[i]);
      }
    }
    //            
    pStmt.setMaxRows(pageIndex*pageSize);
    ResultSet rs = pStmt.executeQuery();
    //              
    rs.relative((pageIndex-1)*pageSize);
    if(rs != null){
      try {
        dataList = new ArrayList<Map<String,Object>>();
        ResultSetMetaData md = rs.getMetaData(); //     (rs)     ,     、     
        //     
        while(rs.next()){
          Map<String, Object> map = new LinkedHashMap();
          for (int i = 1; i <= md.getColumnCount(); i++) {
            map.put(attachTableName?(formatTableName(md.getTableName(i))+"."+md.getColumnLabel(i)):(md.getColumnLabel(i)), rs.getObject(i));
          }
          dataList.add(map);
        }
      }finally{
        if(rs != null){
          rs.close();
        }
        if(pStmt != null){
          pStmt.close();
        }
        if (conn != null) {
          this.closeConnection(conn);
        }
      }
    }
    return dataList;
  }
호출 목록 조회

public static void queryList(){
    String sql = "select u.*,d.* from user u,depart d where u.depart_id=d.id";
    try {
      List<Map<String, Object>> dataList = baseImp.queryForListAttachTableName(2,2,sql, null);
//     List<Map<String, Object>> dataList = baseImp.queryForList(2,2,sql, null);
      for (Map<String, Object> map : dataList) {
        for (String key : map.keySet()) {
          System.out.print(key+"="+map.get(key)+" ");
        }
        System.out.println();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
결실

2.검색 결 과 를 jsonArray 로 되 돌려 줍 니 다.

/**
   *      ArrayList  
   * @param         key     ,  :user.id, id
   * @param sql        :"select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id"
   * @param values
   * @throws SQLException 
   */
  private JSONArray queryJsonArray(int pageIndex,int pageSize,boolean attachTableName,String sql,Object... values) throws SQLException{
    JSONArray jsonArray = null;
    Connection conn = null;
    PreparedStatement pStmt = null;
    //    
    if(pageIndex <= 0){
      pageIndex = 1;
    }
    if(pageSize <= 0){
      pageSize = Config.PAGE_SIZE_DEFAULT;
    }
    conn = this.getConnection(conn);
    pStmt = conn.prepareStatement(sql);
    //    
    if(pStmt != null && values != null && values.length > 0){
      for (int i = 0; i < values.length; i++) {
        pStmt.setObject(i+1, values[i]);
      }
    }
    //            
    pStmt.setMaxRows(pageIndex*pageSize);
    ResultSet rs = pStmt.executeQuery();
    //              
    rs.relative((pageIndex-1)*pageSize);
    if(rs != null){
      try {
        jsonArray = new JSONArray();
        ResultSetMetaData md = rs.getMetaData(); //     (rs)     ,     、     
        //     
        while(rs.next()){
          JSONObject jsonObject = new JSONObject();
          for (int i = 1; i <= md.getColumnCount(); i++) {
            jsonObject.put(attachTableName?(formatTableName(md.getTableName(i))+"."+md.getColumnLabel(i)):(md.getColumnLabel(i)), rs.getObject(i)+"");
          }
          jsonArray.add(jsonObject);
        }
        }finally{
          if(rs != null){
            rs.close();
          }
          if(pStmt != null){
            pStmt.close();
          }
          if (conn != null) {
            this.closeConnection(conn);
          }
        }
    }
    return jsonArray;
  }
jsonArray 조회 호출

public static void queryJsonArray(){
//   String sql = "select * from user u";
    String sql = "select u.*,d.* from user u,depart d where u.depart_id=d.id";
//   String sql = "select u.id AS uid,u.name,u.sex,u.depart_id AS departId,d.name from user u,depart d where u.depart_id=d.id";
//   String sql = "select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id";
    try {
      JSONArray jsonArray = baseImp.queryForJsonArrayAttachTableName(2,2,sql, null);
//     JSONArray jsonArray = baseImp.queryForJsonArray(sql, null);
      System.out.println(jsonArray.toString());
      for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        Iterator<?> iterator = jsonObject.keys();
        Object key = null;
        while (iterator.hasNext()) {
          key = iterator.next();
          System.out.print(key+" "+jsonObject.get(key)+" ");
        }
        System.out.println();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
결실

[{"user.id":"4","user.name":"  ","user.sex":"0","user.depart_id":"3","depart.id":"3","depart.name":"   ","depart.desc":"     "},{"user.id":"5","user.name":"  ","user.sex":"1","user.depart_id":"1","depart.id":"1","depart.name":"   ","depart.desc":"     "}]
user.id 4 user.name    user.sex 0 user.depart_id 3 depart.id 3 depart.name     depart.desc       
user.id 5 user.name    user.sex 1 user.depart_id 1 depart.id 1 depart.name     depart.desc      
3.총 기록 항목 수 조회

/**
   *       
   * @param sql   :"select count(*) from user where xxx"
   * @param values
   * @throws SQLException 
   */
  public int queryCount(String sql,Object... values) throws SQLException{
    int count = -1;
    Connection conn = null;
    PreparedStatement pStmt = null;
    conn = this.getConnection(conn);
    pStmt = conn.prepareStatement(sql);
    //    
    if(pStmt != null && values != null && values.length > 0){
      for (int i = 0; i < values.length; i++) {
        pStmt.setObject(i+1, values[i]);
      }
    }
    ResultSet rs = pStmt.executeQuery();
    if(rs != null){
      try {
        while(rs.next()){
          count = rs.getInt(1);
        }
      }finally{
        if(rs != null){
          rs.close();
        }
        if(pStmt != null){
          pStmt.close();
        }
        if (conn != null) {
          this.closeConnection(conn);
        }
      }
    }
    return count;
  }
호출 조회 총 기록 항목 수

public static void queryCount(){
    String sql = "select count(*) from user u";
    try {
      System.out.println("count="+baseImp.queryCount(sql, null));
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
결실

이로써 자바 기초 개발 에서 JDBC 가 데이터 베 이 스 를 추가 삭제 하고 수정 하 는 작업 과 페이지 별 조 회 를 소 개 했 습 니 다.이 방면 에 관 한 글 을 더 알 고 싶다 면 아래 의 관련 링크 를 보 세 요.

좋은 웹페이지 즐겨찾기