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
Connection
orStatement
level. - Is it safe that 'one'
Connection
create 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.