hibernate---查詢所需列的實現代碼

	
/** 裝載制定類的所有持久化對象*/
	public List listAll(String clazz, String[] colmunNames){
		// select empId,empName from employee
		String sql = "select ";
		for (String colmun : colmunNames) {
			sql += colmun+',';
		}
		// 去除最後一個列名後的逗號
		sql = sql.substring(0, sql.length()-1)+" from "+clazz;
		List list = new ArrayList();
		//連接數據庫的3個對象
		Connection conn = null;
		ResultSet rst = null;
		PreparedStatement pst = null;
		try {
			//獲取連接
			conn = DaoFactory.getConn();
			pst = conn.prepareStatement(sql);
			//執行SQL
			rst = pst.executeQuery();
			while(rst.next()) {
				String str = new String();
				//循環讀取列對象
				for (String string : colmunNames) {
					str+=rst.getString(string)+":";
				}
				list.add(str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoFactory.closeAll(conn, pst, rst);
		}
		return list;
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章