最近做一個基于J2EE的WEB項目,該項目的特點是查詢比較多,本來設計中打算用hibernate實現持久層,但是基于項目時間緊張和開發人員不熟悉hibernate而取消.于是想到了傳統的Dao,加上最近看了好多關于類反射的東西,于是自己寫了一個簡單的Dao,基本的方法很簡單,輸入sql語句/參數/,返回String二維數組(直接在頁面顯示).由于只是針對web顯示,所以在設計上加入了一些小技巧,例如數組的第一行是表頭信息,通過參數傳入,如果參數為null則根據dbms metadata來讀取,相關的api列表如下:
其中以Simple開頭的查詢方法只支持單條查詢并直接返回結果,其打開和關閉連接等過程在內部自動實現.以exec開頭的的方法支持多條查詢和update,支持事務,要自己打開(init)和關閉(close)連接,下面是一個stuts actionbean里面的代碼片斷,是不是看起來很簡單呢:)
? Dao d = new Dao();
??String[][] result = null;
??String sql="select name,phone from users where schoolID=? and classID=?"
??result=d.simplyQuery(sql,
????new String[]{"姓名","電話號碼"},? //表頭
????new String[]{theForm.getSchoolID(),theForm.getClassID}?? //參數
????);
??request.getSession().setAttribute("xxxx..",result);
Feedback
request.getSession().setAttribute("xxxx..",result);
很錯誤的用法
很錯誤的用法
放到session之前就已經關閉掉了
public String[][] simplyQuery(String sql,String[] titles,Object[] params)
{
try {
this.init();
return this.execSQL(sql,titles,params);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getMessage());
return null;
}
finally
{
this.close();
}
}
public String[][] simplyQuery(String sql,String[] titles,Object[] params)
{
try {
this.init();
return this.execSQL(sql,titles,params);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getMessage());
return null;
}
finally
{
this.close();
}
}
只有注冊用戶登錄后才能發表評論。 | ||
![]() |
||
網站導航:
博客園
IT新聞
Chat2DB
C++博客
博問
管理
|
||