KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JdbcExample


1 /*
2  * @(#) JdbcExample.java
3  *
4  *
5  * JOTM: Java Open Transaction Manager
6  *
7  *
8  * This module was orginally developed by
9  *
10  * - INRIA (www.inria.fr)inside the ObjectWeb Consortium
11  * (http://www.objectweb.org)
12  *
13  * --------------------------------------------------------------------------
14  * The original code and portions created by INRIA are
15  * Copyright (c) 2002 INRIA
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions are met:
20  *
21  * -Redistributions of source code must retain the above copyright notice, this
22  * list of conditions and the following disclaimer.
23  *
24  * -Redistributions in binary form must reproduce the above copyright notice,
25  * this list of conditions and the following disclaimer in the documentation
26  * and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
29  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
32  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  *
40  * --------------------------------------------------------------------------
41  * $Id: JdbcExample.java,v 1.2 2003/12/05 19:03:56 trentshue Exp $
42  * --------------------------------------------------------------------------
43  */

44
45 import java.sql.Connection JavaDoc;
46 import java.sql.PreparedStatement JavaDoc;
47 import java.sql.ResultSet JavaDoc;
48 import java.sql.Statement JavaDoc;
49
50 import javax.naming.Context JavaDoc;
51 import javax.naming.InitialContext JavaDoc;
52 import javax.transaction.UserTransaction JavaDoc;
53
54 /**
55  * @author jmesnil
56  *
57  * This class is an example of use of JOTM with a DataBase
58  */

59 public class JdbcExample {
60
61     private static final String JavaDoc USAGE = "usage: java JdbcExample [database] [commit|rollback] [number]";
62     private static final String JavaDoc SQL_REQUEST = "select id, foo from testdata";
63     private static final String JavaDoc SQL_QUERY = "update testdata set foo = ? where id=1";
64     private static final String JavaDoc USER_TRANSACTION_JNDI_NAME = "UserTransaction";
65     private static Connection JavaDoc conn = null;
66
67     private static void printTable() {
68         try {
69             Statement JavaDoc stmt = conn.createStatement();
70             ResultSet JavaDoc rset = stmt.executeQuery(SQL_REQUEST);
71             int numcols = rset.getMetaData().getColumnCount();
72             for (int i = 1; i <= numcols; i++) {
73                 System.out.print("\t" + rset.getMetaData().getColumnName(i));
74             }
75             System.out.println();
76             while (rset.next()) {
77                 for (int i = 1; i <= numcols; i++) {
78                     System.out.print("\t" + rset.getString(i));
79                 }
80                 System.out.println("");
81             }
82         } catch (Exception JavaDoc e) {
83             e.printStackTrace();
84         }
85     }
86
87     private static void updateTable(int newValue) {
88         try {
89             PreparedStatement JavaDoc pstmt = conn.prepareStatement(SQL_QUERY);
90             pstmt.setInt(1, newValue);
91             pstmt.executeUpdate();
92         } catch (Exception JavaDoc e) {
93             e.printStackTrace();
94         }
95     }
96
97     public static void main(String JavaDoc[] args) {
98
99         if (args.length != 3 || (!args[1].equals("commit") && !args[1].equals("rollback"))) {
100             System.out.println(USAGE + "\n");
101             System.exit(1);
102         }
103
104         String JavaDoc completion = args[1];
105
106         int newValue = 0;
107         try {
108             newValue = Integer.parseInt(args[2]);
109         } catch (NumberFormatException JavaDoc e) {
110             System.out.println(USAGE);
111             System.out.println("[number] has to be an integer\n");
112             System.exit(1);
113         }
114
115         System.out.println("start server");
116         DatabaseHelper dbHelper = new DatabaseHelper(args[0]);
117
118         UserTransaction JavaDoc utx = null;
119         try {
120             System.out.println("create initial context");
121             Context JavaDoc ictx = new InitialContext JavaDoc();
122             System.out.println("lookup UserTransaction at : " + USER_TRANSACTION_JNDI_NAME);
123             utx = (UserTransaction JavaDoc) ictx.lookup(USER_TRANSACTION_JNDI_NAME);
124         } catch (Exception JavaDoc e) {
125             System.out.println("Exception of type :" + e.getClass().getName() + " has been thrown");
126             System.out.println("Exception message :" + e.getMessage());
127             e.printStackTrace();
128             System.exit(1);
129         }
130
131         try {
132             System.out.println("get a connection");
133             conn = dbHelper.getConnection();
134         } catch (Exception JavaDoc e) {
135             e.printStackTrace();
136         }
137
138         System.out.println("before transaction, table is:");
139         printTable();
140
141         try {
142             System.out.println("begin a transaction");
143             utx.begin();
144
145             System.out.println("update the table");
146             updateTable(newValue);
147
148             if (completion.equals("commit")) {
149                 System.out.println("*commit* the transaction");
150                 utx.commit();
151             } else {
152                 System.out.println("*rollback* the transaction");
153                 utx.rollback();
154             }
155         } catch (Exception JavaDoc e) {
156             System.out.println("Exception of type :" + e.getClass().getName() + " has been thrown");
157             System.out.println("Exception message :" + e.getMessage());
158             e.printStackTrace();
159             System.exit(1);
160         }
161
162         utx = null;
163
164         System.out.println("after transaction, table is:");
165         printTable();
166
167         try {
168             System.out.println("close connection");
169             conn.close();
170
171         } catch (Exception JavaDoc e) {
172             e.printStackTrace();
173         } finally {
174             conn = null;
175         }
176
177         System.out.println("stop server");
178         dbHelper.stop();
179
180         System.out.println("JDBC example is ok.\n");
181         System.exit(0);
182     }
183 }
184
Popular Tags