gpt4 book ai didi

java - 查询两个独立的数据库。你如何处理两个连接?

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:17 25 4
gpt4 key购买 nike

我必须编写一个 Servlet 来获取用户 ID 和名称,以及用户的名字和姓氏。我们必须验证的用户信息位于名为 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 代码

这是需要完成的事情吗,或者我可以在一个类中完成这一切,就像我在正常的单个数据库查询中所做的那样(我已经被证明是这样做的):

连接到数据库

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

感谢您的帮助!

最佳答案

读取数据很简单。如果您需要在一个 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

如果您需要阅读其中任何一个,那么,根据参数决定并仅执行上面的 block 之一。

关闭连接和其他东西最好在finally block 中,以避免发生异常时的泄漏。

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

关于java - 查询两个独立的数据库。你如何处理两个连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5691214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com