I have to write a Servlet that gets a user id and name, and a user first name and last name. The user info that we开发者_运维百科 have to verify is on a database called userinfo
, and the information on the people we are looking for is held on a database called people
.
How do I handle two separate db queries? Do I need to make two separate classes (one for each db connection) and then write my Servlet along the lines of (obviously not correct syntax - just looking at concepts):
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 code written back by the servlet
Is that what needs to be done, or can I do it all in one class like I would off of a normal single DB query (I have been shown to do it like this):
connect to 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
Thanks for any help!
Reading data is simple. If you need to read both databases in one HTTP request, then:
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
If you need to read either, well, decide based on parameters and execute only one of the blocks above.
Closing connections and other stuff is better in finally block to avoid leaks in case of exceptions.
The big problem is when you need to update two databases in a consistent way, i.e. if update to db2 fails, update to db1 would not be committed. For that you must get an distributed/global transactions support. The most common way is to migrate from a servlet container to an EJB container, and have you code run within a session bean with required transaction.
精彩评论