Direct JDBC calls, local transaction

This can group several statements in a unit of work with setAutoCommit set to false, as shown in Example 12-2.

Example 12-2 StaleConnectionException with direct JDBC calls and local transaction

...
	javax.sql.DataSource ds=null;
	java.sql.Connection conn=null;
	java.sql.Statement stmt1=null;
	java.sql.ResultSet rs=null;
	int maxRetries=5; // set maximum number of retries
	int noRetries=0;
	int bal=0;
	boolean retry=false;

	do {
		try { //already lookup datasource object ds, see above section
			conn=ds.getConnection();
			conn.setAutoCommit(false);
			stmt1=conn.createStatement();
			rs=stmt1.executeQuery(sqlstring1);
			bal=rs.getInt(3);
			stmt1.executeUpdate(sqlstring2);
			conn.commit();
		} catch ( com.ibm.websphere.ce.cm.StaleConnectionException staleex) {
			//rollback
			try{
				conn.rollback();
				if (noRetries <= maxRetries) {
					// retry upto maxRetries times
					try {
						Thread.sleep(1000 + 20000*noRetries);
						// with increasing retry interval
						// preserve cpu cycle
					} catch (InterruptedException iex) {
						System.out.println(
							"Sleep Interruppted" + iex.getMessage());
					}
					noRetries++;
					retry=true;
				} else {
					retry=false;
					// don't retry after maxRetries times
				}
			} catch (Exception ex) {
				retry=false;
				//rollback failed, don't retry
			}
		} catch (java.sql.SQLException sqlex) {
			//other sql exception, don't retry
			retry=false;
		} catch ( Exception ex) {
			// generic exception, don't retry
			retry=false;
		} finally {
			try {
				if (rs!=null) rs.close();
				if (stmt1!=null) stmt1.close();
				if (conn!=null) conn.close();
			} catch (Exception ex) {}
		}
	} while (retry);
...

  Prev | Home | Next

 

WebSphere is a trademark of the IBM Corporation in the United States, other countries, or both.

 

IBM is a trademark of the IBM Corporation in the United States, other countries, or both.