java - JNDI, DBCP, JDBC & MySQL by Example -


i'm trying to:

  1. read mysql datasource out of jndi
  2. use jndi datasource configure dbcp connection pool jdbc connection
  3. fire sql statement using jdbc
  4. close politely (release connection pool, close else out, etc.)

this code fired a lot (its simple logging system app), , can kept open across multiple sql executions preferably left open (to reduce overhead of opening/closing stuff, etc.).

here's best attempt:

    try {         // 1. obtain dblogger datasource jndi.         context context = new initialcontext();         datasource logdatabaseds = (datasource)context.lookup(logdatabasejndi);          // 2. configure connection pool jndi datasource.         // how?          // 3. obtain connection pool.         // how?          // 4. use connection fire jdbc insert.         class.forname("com.mysql.jdbc.driver");         connection conn = drivermanager.getconnection("urlfromjndi",                  "userfromjndi", "passwordfromjndi");          preparedstatement statement = conn.preparestatement(insertsql);         statement.setstring(1, appname);         statement.setlong(2, timestamp);         statement.setstring(3, loglevel);          statement.executeupdate();          // 5. release borrowed connection pool.         // how?     } catch (sqlexception e) {         e.printstacktrace();     } catch (classnotfoundexception e) {         e.printstacktrace();     } catch (namingexception e) {         e.printstacktrace();     }  

i believe have basic setup correct. not sure of:

  1. how configure dbcp pool using jndi-set properties (like maxidle, maxwait, etc.)
  2. borrow connection dbcp pool in efficient way (so code fires dozens/hundreds of times per second , not leak resources)
  3. inject connection string url, username , password jndi datasource drivermanager.getconnection(...) method
  4. politely/correctly release connection pool.

and, if haven't set process correctly, please begin correcting me on general approach first! again!


Comments