Connecting Tech Pros Worldwide Forums | Help | Site Map

Transaction attempt not working

Newbie
 
Join Date: Aug 2007
Posts: 20
#1: Oct 16 '07
I am trying to get Transaction working with JDBC and Oracle database. In my below example, if I try and fail the second insert by putting in an invalid table name (called BadTableName), the rollback doesnt work because the first insert makes it into the database. Please advise how I can get this to work:

Expand|Select|Wrap|Line Numbers
  1. public class Serra
  2. {
  3. ....
  4. public PreparedStatement prep;
  5. ..
  6.  
  7. public int methodOne(City city)
  8. {
  9.    int one = 0;
  10.    try
  11.   {
  12.       prep = connection.prepareStatement("insert into States (fieldOne,fieldTwo) values (?,?)");
  13.       prep.setString(1, city.getFieldOne());
  14.       prep.setString(2, city.getFieldTwo());
  15.       prep.executeUpdate();
  16.    }
  17.    catch(Exception e)
  18.   {
  19.       e.printStackTrace();
  20.   }
  21.   return one;
  22. }
  23.  
  24.  
  25. public int methodTwo(City city)
  26. {
  27.    int two = 0;
  28.    try
  29.   {
  30.       prep = connection.prepareStatement("insert into BadTableName (fieldThree,fieldFour) values (?,?)");
  31.       prep.setString(1, city.getFieldThree());
  32.       prep.setString(2, city.getFieldFour());
  33.       prep.executeUpdate();
  34.    }
  35.    catch(Exception e)
  36.   {
  37.       e.printStackTrace();
  38.   }
  39.   return two;
  40. }
  41.  
  42. ...
  43.  
  44. public int mainInsert(City city)
  45. {
  46.      try
  47.      {
  48.                 connection.setAutoCommit(false);
  49.                 methodOne(city);
  50.     methodTwo(city);
  51.                 connection.commit();
  52.      }
  53.      catch (SQLException ex)
  54.      {
  55.           try
  56.           {
  57.               connection.rollback();
  58.          }
  59.          catch(Exception e)
  60.          {
  61.               e.printStackTrace();
  62.          }
  63.          ex.printStackTrace();
  64.      }
  65.      finally
  66.      { 
  67.         //closing part here for the ResultSet, Statement and Connection
  68.      }
  69.  
  70.  

Reply