PageRenderTime 35ms CodeModel.GetById 16ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 1ms

/web/DRCP/src/foo/DBTest.java

http://drcp.googlecode.com/
Java | 70 lines | 51 code | 15 blank | 4 comment | 6 complexity | f481133878ba8f9f70d4c618d2ddd573 MD5 | raw file
 1package foo;
 2
 3import java.sql.PreparedStatement;
 4import java.sql.ResultSet;
 5import java.sql.Statement;
 6
 7import javax.naming.Context;
 8import javax.naming.InitialContext;
 9import javax.sql.DataSource;
10import javax.transaction.UserTransaction;
11
12public class DBTest{
13
14    int foo = -1;
15    // value stored in DB
16
17    public void init(String completion) {
18        try{
19            Context ctx = new InitialContext();
20
21            // JDBC stuff
22            DataSource ds =
23                (DataSource)ctx.lookup("java:comp/env/jdbc/myDB");
24
25            UserTransaction ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction");
26
27            java.sql.Connection conn = ds.getConnection();
28
29            System.out.println("<<< beginning the transaction >>>");
30            ut.begin();
31
32             // JDBC statements
33             Statement stmt = conn.createStatement();
34             ResultSet rst =
35                 stmt.executeQuery("select id, foo from testdata");
36             if(rst.next()) {
37                 foo=rst.getInt(2);
38             }
39             System.out.println("foo = "+ foo +" (before completion)");
40
41             PreparedStatement pstmt = conn.prepareStatement("update testdata set foo=? where id=1");
42             pstmt.setInt(1,++foo);
43             pstmt.executeUpdate();
44
45              if (completion != null && completion.equals("commit")) {
46                  System.out.println("<<< committing the transaction >>>");
47                  ut.commit();
48              } else {
49                  System.out.println("<<< rolling back the transaction >>>");
50                  ut.rollback();
51              }
52
53             // we set foo to the value stored in the DB
54             rst =
55                 stmt.executeQuery("select id, foo from testdata");
56             if(rst.next()) {
57                 foo=rst.getInt(2);
58             }
59             System.out.println("foo = "+ foo +" (after completion)");
60
61             conn.close();
62             System.out.println("<<< done >>>");
63        }catch(Exception e) {
64            System.out.print("DBTest >> ");
65            e.printStackTrace();
66        }
67    }
68
69    public String getFoo() { return ""+foo; }
70}