/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

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