2011-04-17 67 views
1

我必須編寫一個獲取用戶ID和名稱以及用戶名和姓的Servlet。我們必須驗證的用戶信息位於名爲userinfo的數據庫中,我們正在查找的人員信息保存在名爲people的數據庫中。查詢兩個單獨的數據庫。你如何處理兩個連接?

如何處理兩個單獨的數據庫查詢?我需要做兩個獨立的類(每個數據庫連接),然後寫我的Servlet沿線的(顯然不是正確的語法 - 只看概念):

if (connection to UserinfoDB) 
{ 
    //code for the handling of correct or for mismatching id and password 
} 

if (connection to PeopleDB) 
{ 
    //code for handling the proper input of last name and first name off of the second connection 
} 

HTML代碼由servlet寫回

是需要做什麼,或者我可以做到這一切在一類像我會掉一個正常的單DB查詢(我已經被證明不喜歡這樣):

連接到數據庫

doPost 
{ 
    //1. get info from servlet form 

    //2. query the DB 

    //3. insert something into the db or whatever you are doing 
} 

//print some HTML feedback from the servlet 

//close the db connect 

感謝您的幫助!

回答

1

讀取數據很簡單。如果你需要在一個HTTP請求中讀取這兩個數據庫,則:

get connection to db1 
prepare statement 
execute it and get results, save them to local variables 
close resultset, statement, connection to db1 

get connection to db2 
prepare statement 
execute it and get results, save them to local variables 
close resultset, statement, connection to db2 

如果您需要任何閱讀,那麼,根據跟蹤參數及執行只以上的區塊之一。

關閉連接和其他東西在終止時更好,以避免在例外情況下發生泄漏。

最大的問題是,當你需要更新兩個數據庫以一致的方式,即,如果更新DB2失敗,更新DB1將承諾。爲此,您必須獲得分佈式/全局事務支持。最常見的方式是從servlet容器遷移到EJB容器,並讓您在具有必需事務的會話bean中運行代碼。