I was always using JDBC in JavaSE on single-threaded environment. But now I need to use a connection pool and let many threads to have interaction with the database (MSSQL and Oracle) and I am having a hard time trying to make it as it seems that I am lacking some fundamental undestanding of the api.
AFAIK after connect and logging a Connection represents a phisical tcp/ip connection to the database. It creates Statement(s) that can be seen as SQL interaction(s) with the database over the Connection.
- Where does the transaction and rollback comes in ? Is it at the
ConnectionorStatementlevel. - Is it safe that ‘one’
Connectioncreate N statements and give it to diferent threads so to let each one own the use of thatStatement?
If not, and after configuring the pool something like this:
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:@tnsentryname");
ods.setUser("u");
ods.setPassword("p");
-
BTW, where do I set the connection pool size ?
-
Is this what I would be doing in each thread in order to correctly use the connection ?
//thead run method
Connection conn = ods.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("the sql");
// do what I need to do with rs
rs.close();
int updateStatus = stmt.executeUpdate("the update");
stmt.close();
conn.close();
// end of thread run method
- If any physical Connection of the Pool somehow crashes or disconects, will the pool automaticaly try to reconnect and inject the new connection in the pool so that subsequent pool.getConnection() will just get a health connection ?
Thanks a lot and forgive my bad english please.
Connection pools decorate Connection and Statement instances with their own wrapper implementations. When you call close on a connection you are actually just releasing it back to the pool. When you call close on a prepared statement you are actually just releasing it back to the connection’s statement cache. When you prepare a statement you might just be fetching a cached statement instance from the connection. All this is hidden from view so that you don’t have to worry about it.
When a connection is given to a client it is no longer available for any other client to use until the connection is released back to the pool. You generally just fetch connections when you need them and then return them as soon as you are finished with them. Because the connections are being held open in the pool there is little overhead in fetching and releasing connections.
You should use a connection from the pool just as you would a single JBDC connection and follow best-practices regarding the closing of resources so that you do not leak any connections or statements. See the try/catch/finally examples in some of the other answers.
Pools can manage the connection resources and test them before handing them out to clients to ensure that they aren’t stale. Also a pool will create and destroy connections as needed.