1 43 44 package foo; 45 46 import java.sql.PreparedStatement ; 47 import java.sql.ResultSet ; 48 import java.sql.Statement ; 49 50 import javax.naming.Context ; 51 import javax.naming.InitialContext ; 52 import javax.sql.DataSource ; 53 import javax.transaction.UserTransaction ; 54 55 public class DBTest{ 56 57 int foo = -1; 58 60 public void init(String completion) { 61 try{ 62 Context ctx = new InitialContext (); 63 64 DataSource ds = 66 (DataSource )ctx.lookup("java:comp/env/jdbc/myDB"); 67 68 UserTransaction ut = (UserTransaction )ctx.lookup("java:comp/UserTransaction"); 69 70 java.sql.Connection conn = ds.getConnection(); 71 72 System.out.println("<<< beginning the transaction >>>"); 73 ut.begin(); 74 75 Statement stmt = conn.createStatement(); 77 ResultSet rst = 78 stmt.executeQuery("select id, foo from testdata"); 79 if(rst.next()) { 80 foo=rst.getInt(2); 81 } 82 System.out.println("foo = "+ foo +" (before completion)"); 83 84 PreparedStatement pstmt = conn.prepareStatement("update testdata set foo=? where id=1"); 85 pstmt.setInt(1,++foo); 86 pstmt.executeUpdate(); 87 88 if (completion != null && completion.equals("commit")) { 89 System.out.println("<<< committing the transaction >>>"); 90 ut.commit(); 91 } else { 92 System.out.println("<<< rolling back the transaction >>>"); 93 ut.rollback(); 94 } 95 96 rst = 98 stmt.executeQuery("select id, foo from testdata"); 99 if(rst.next()) { 100 foo=rst.getInt(2); 101 } 102 System.out.println("foo = "+ foo +" (after completion)"); 103 104 conn.close(); 105 System.out.println("<<< done >>>"); 106 }catch(Exception e) { 107 System.out.print("DBTest >> "); 108 e.printStackTrace(); 109 } 110 } 111 112 public String getFoo() { return ""+foo; } 113 } 114 115 | Popular Tags |