查询两个单独的DB。你如何处理两个连接?

时间:2011-04-17 03:20:22

标签: java servlets

我必须编写一个获取用户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
}

servlet写回的HTML代码

这是需要做什么的,或者我可以在一个类中完成所有操作,就像我在正常的单个数据库查询中一样(我已经证明这样做了):

连接到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 个答案:

答案 0 :(得分: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

如果你需要阅读,那么,根据参数决定并只执行上面的一个块。

关闭连接和其他东西在finally块中更好,以避免在异常情况下泄漏。

最大的问题是当您需要以一致的方式更新两个数据库时,即如果更新到db2失败,则更新到db1将提交。为此,您必须获得分布式/全局事务支持。最常见的方法是从servlet容器迁移到EJB容器,并让代码在具有所需事务的会话bean中运行。