Lesson 6 | Making a JDBC Connection: Once, or every time? |
Objective | Describe at what point in the code to open and close the connection to a database. |
Making JDBC Connection
Making a connection to a DSN is remarkably simple. Before you see the code, though, you need to think about how often that connection should be opened and closed. There are two approaches to maintaining a database connection:
- Make the connection in the servlets
init()
method. The connection will stay open throughout the life of the servlet object.
- Make the connection in the servlets
doPost()
method, and close it in the same method.
Connect in init()
Remember, unlike CGI programs, servlets are very long-lived and use threads to handle multiple requests.
The consequences of this are that any resource, such as a database connection, that belongs to the servlet will be used by multiple requests, perhaps multiple requests at the same time.
JDBC Resource Drain
Connect in doPost()
Perhaps you would like your servlet to connect to a different database to handle different kinds of requests, or to handle requests from users with different levels of authority, or maybe most of the work your servlet does has no need of a database. In that case, you should open those connections just before you deal with the request, and close them immediately afterwards. Are you concerned about the resource drain involved in each servlet hanging onto a database connection at all times?
You might prefer to get those connections just before you need them, and let go immediately afterwards.
For most work, the performance costs associated with opening a connection outweigh other considerations.
By opening the connection once, in the init()
method, you pay this cost only once and other servlet requests can just use the open connection. In the next lesson, I will show you how to do this in init(), but remember you could move this code to doPost()
if you prefer.
In the next lesson, you will see the code to connect to a data source.