歡迎您光臨本站 註冊首頁

將ResultSet中得到的一行或多行結果集封裝成物件的例項

←手機掃碼閱讀     limiyoyo @ 2020-05-03 , reply:0

首先說一下這個使用場景,我們在使用jdbc連線資料庫的時候,執行查詢語句時候會得到一個結果集,如果想要再獲取這個結果集中的值,就需要我們將他轉換成一個物件,然後透過物件的get和set方法來獲取到資料庫中的值。
public class BaseDao

{ private Class cls; public BaseDao() { //得到父類的泛型 Type sType=getClass().getGenericSuperclass(); //得到實際的型別引數陣列 Type[] generics=((ParameterizedType) sType).getActualTypeArguments(); //得到第一個泛型的Class cls=(Class) (generics[0]); }
/** * 單表多條查詢,將查詢到的多條記錄傳入一個物件,然後再將這些存入一個集合中,返回這個集合 * @param sql 傳入對應的sql查詢語句 * @param parameters 傳入對應的佔位符的值 * @return 返回查詢到的記錄轉化成的物件的集合 */ //Object...parameters是sql語句中對應的佔位符的值,是一個不定長可變引數,我們需要寫一個函式來獲取他 public Listlist(String sql,Object...parameters) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; Listlist = new ArrayList<>(); try { conn = JdbcUtil.getConnection(); st = conn.prepareStatement(sql); setParameters(st, parameters); rs = st.executeQuery(); while(rs.next()) { //將獲取到的結果集存入一個物件中,這個我們也單獨寫一個函式來實現 E obj = oneRowToObject(rs); //然後將物件存入一個集合中返回 list.add(obj); } } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtil.closeAll(rs, st, conn); } return list; }
首先來寫一下獲取不定長可變引數的方法
/** * 設定佔位符 * @param st 預處理 * @param parameters 佔位符陣列 * @return 返回儲存佔位符對應的物件的陣列 */ private void setParameters(PreparedStatement st, Object[] parameters) { //判斷是否有結果集,結果集中是否有記錄 if(parameters!=null&¶meters.length>0) { for(int i=0;i<parameters.length;i++) { try { st.setObject(i+1,parameters[i] ); } catch (SQLException e) { e.printStackTrace(); } } } }
然後再把一個結果集轉化成一個物件的方法寫一下

* 把得到的一列資料存入到一個物件中 

* @param rs 

* @return 

* @throws InstantiationException 

* @throws IllegalAccessException 

* @throws SQLException 

* @throws NoSuchMethodException 

* @throws SecurityException 

* @throws IllegalArgumentException 

* @throws InvocationTargetException 

*/ @SuppressWarnings("unchecked") private E oneRowToObject(ResultSet rs) throws InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { E obj; obj=(E) cls.newInstance();

 //獲取結果集後設資料(獲取此 ResultSet 物件的列的編號、型別和屬性。) ResultSetMetaData rd=rs.getMetaData(); 

for (int i = 0; i < rd.getColumnCount(); i++) { 

//獲取列名

 String columnName=rd.getColumnLabel(i+1); //組合方法名 String methodName="set"+columnName.substring(0, 1).toUpperCase()+columnName.substring(1); //獲取列型別 

int columnType=rd.getColumnType(i+1); Method method=null; switch(columnType) {

 case java.sql.Types.VARCHAR:

 case java.sql.Types.CHAR: method=cls.getMethod(methodName, String.class);

 if(method!=null) { method.invoke(obj, rs.getString(columnName)); } break; 

case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: method=cls.getMethod(methodName, int.class); 

if(method!=null) { method.invoke(obj, rs.getInt(columnName)); } break; case java.sql.Types.BIGINT: 

method=cls.getMethod(methodName, long.class); if(method!=null) { method.invoke(obj, rs.getLong(columnName)); } break; case java.sql.Types.DATE: case java.sql.Types.TIMESTAMP: try { method=cls.getMethod(methodName, Date.class); if(method!=null) { method.invoke(obj, rs.getTimestamp(columnName)); } } 

catch(Exception e) { method=cls.getMethod(methodName, String.class); if(method!=null) { method.invoke(obj, rs.getString(columnName)); } } break; case java.sql.Types.DECIMAL: method=cls.getMethod(methodName, BigDecimal.class); if(method!=null) { method.invoke(obj, rs.getBigDecimal(columnName)); } break; case java.sql.Types.DOUBLE: case java.sql.Types.NUMERIC: method=cls.getMethod(methodName, double.class); if(method!=null) { method.invoke(obj, rs.getDouble(columnName)); } break; case java.sql.Types.BIT: method=cls.getMethod(methodName, boolean.class); if(method!=null) { method.invoke(obj, rs.getBoolean(columnName)); } break; default: break; } } return obj; }

使用的話就是寫一個實體類Dao繼承BaseDao
public class UserDao extends BaseDao{
}
測試一下:

public class test { 

public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, SQLException, IntrospectionException { UserDao userdao = new UserDao(); Listlist=userdao.list("select * from user"); System.out.println("uid "+"uname "+"state "+"flag"); for (User user : list) { System.out.println(user.getUid()+" "+user.getUname()+" "+user.getState()+" "+user.getFlag()); } } }


[limiyoyo ] 將ResultSet中得到的一行或多行結果集封裝成物件的例項已經有275次圍觀

http://coctec.com/docs/program/show-post-232593.html