Java JDBC technology using reflection result of the query object encapsulation

1, JDBC returns a result set objects packaged into demo

     class JdbcDemo { 

        / ** 
         * Retrieves the database column names 
         * @param   RS 
         * @return 
         * / 
         Private  static String [] getColNames (the ResultSet RS) throws SQLException { 
             the ResultSetMetaData rsmd = rs.getMetaData ();
              // Get the number of columns of the query 
             int = COUNT rsmd.getColumnCount (); 
             String [] colNames = new new String [COUNT];
              for ( int I =. 1; I <= COUNT; I ++ ) {
                  // Get the name of the column
                 colNames [I -. 1] = rsmd.getColumnLabel (I); 
             } 
             return colNames; 
         } 

         / ** 
          * returns the query result set of JDBC, encapsulated into objects using reflection 
          * @param SQL 
          * @param clazz 
          * @return 
          * / 
         Private  static Object the getObject (String SQL, Class clazz) { 
             Connection Conn = null ; 
             the PreparedStatement PS = null ; 
             the ResultSet RS = null ; 

             the try { 
                 Conn= JdbcUtils.getConnection();
                 ps = conn.prepareStatement(sql);
                 rs = ps.executeQuery();
                 String[] colNames = getColNames(rs);

                 Object object = null;
                 Method[] ms = clazz.getMethods();
                 if(rs.next()) {
                     object = clazz.newInstance();
                     for(int i = 0; i < colNames.length; i ++) {
                         ColName String = colNames[i];
                         MethodName String = "the SET" + colName;
                          // sound a little. Is there a method in the object query this method is called 
                         for (Method, MD: MS) {
                              IF (methodName.equals (md.getName ())) { 
                                 md.invoke (Object, rs.getObject (colName)); 
                                 BREAK ; 
                             } 
                         } 
                     } 
                 } 
                 return Object; 
             } the finally {
                  // release the connection 
                 JdbcUtils.free (RS, PS, Conn); 
             } 
         }
        
     }

 

Guess you like

Origin www.cnblogs.com/chenweichu/p/11128616.html