KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JDBCAdapter


1 /*
2  * @(#)JDBCAdapter.java 1.17 05/11/17
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 /*
38  * @(#)JDBCAdapter.java 1.17 05/11/17
39  */

40
41 /**
42  * An adaptor, transforming the JDBC interface to the TableModel interface.
43  *
44  * @version 1.20 09/25/97
45  * @author Philip Milne
46  */

47
48 import java.util.Vector JavaDoc;
49 import java.sql.*;
50 import javax.swing.table.AbstractTableModel JavaDoc;
51 import javax.swing.event.TableModelEvent JavaDoc;
52
53 public class JDBCAdapter extends AbstractTableModel JavaDoc {
54     Connection connection;
55     Statement statement;
56     ResultSet resultSet;
57     String JavaDoc[] columnNames = {};
58     Vector JavaDoc rows = new Vector JavaDoc();
59     ResultSetMetaData metaData;
60
61     public JDBCAdapter(String JavaDoc url, String JavaDoc driverName,
62                        String JavaDoc user, String JavaDoc passwd) {
63         try {
64             Class.forName(driverName);
65             System.out.println("Opening db connection");
66
67             connection = DriverManager.getConnection(url, user, passwd);
68             statement = connection.createStatement();
69         }
70         catch (ClassNotFoundException JavaDoc ex) {
71             System.err.println("Cannot find the database driver classes.");
72             System.err.println(ex);
73         }
74         catch (SQLException ex) {
75             System.err.println("Cannot connect to this database.");
76             System.err.println(ex);
77         }
78      }
79
80     public void executeQuery(String JavaDoc query) {
81         if (connection == null || statement == null) {
82             System.err.println("There is no database to execute the query.");
83             return;
84         }
85         try {
86             resultSet = statement.executeQuery(query);
87             metaData = resultSet.getMetaData();
88
89             int numberOfColumns = metaData.getColumnCount();
90             columnNames = new String JavaDoc[numberOfColumns];
91             // Get the column names and cache them.
92
// Then we can close the connection.
93
for(int column = 0; column < numberOfColumns; column++) {
94                 columnNames[column] = metaData.getColumnLabel(column+1);
95             }
96
97             // Get all rows.
98
rows = new Vector JavaDoc();
99             while (resultSet.next()) {
100                 Vector JavaDoc newRow = new Vector JavaDoc();
101                 for (int i = 1; i <= getColumnCount(); i++) {
102                 newRow.addElement(resultSet.getObject(i));
103                 }
104                 rows.addElement(newRow);
105             }
106             // close(); Need to copy the metaData, bug in jdbc:odbc driver.
107
fireTableChanged(null); // Tell the listeners a new table has arrived.
108
}
109         catch (SQLException ex) {
110             System.err.println(ex);
111         }
112     }
113
114     public void close() throws SQLException {
115         System.out.println("Closing db connection");
116         resultSet.close();
117         statement.close();
118         connection.close();
119     }
120
121     protected void finalize() throws Throwable JavaDoc {
122         close();
123         super.finalize();
124     }
125
126     //////////////////////////////////////////////////////////////////////////
127
//
128
// Implementation of the TableModel Interface
129
//
130
//////////////////////////////////////////////////////////////////////////
131

132     // MetaData
133

134     public String JavaDoc getColumnName(int column) {
135         if (columnNames[column] != null) {
136             return columnNames[column];
137         } else {
138             return "";
139         }
140     }
141
142     public Class JavaDoc getColumnClass(int column) {
143         int type;
144         try {
145             type = metaData.getColumnType(column+1);
146         }
147         catch (SQLException e) {
148             return super.getColumnClass(column);
149         }
150
151         switch(type) {
152         case Types.CHAR:
153         case Types.VARCHAR:
154         case Types.LONGVARCHAR:
155             return String JavaDoc.class;
156
157         case Types.BIT:
158             return Boolean JavaDoc.class;
159
160         case Types.TINYINT:
161         case Types.SMALLINT:
162         case Types.INTEGER:
163             return Integer JavaDoc.class;
164
165         case Types.BIGINT:
166             return Long JavaDoc.class;
167
168         case Types.FLOAT:
169         case Types.DOUBLE:
170             return Double JavaDoc.class;
171
172         case Types.DATE:
173             return java.sql.Date JavaDoc.class;
174
175         default:
176             return Object JavaDoc.class;
177         }
178     }
179
180     public boolean isCellEditable(int row, int column) {
181         try {
182             return metaData.isWritable(column+1);
183         }
184         catch (SQLException e) {
185             return false;
186         }
187     }
188
189     public int getColumnCount() {
190         return columnNames.length;
191     }
192
193     // Data methods
194

195     public int getRowCount() {
196         return rows.size();
197     }
198
199     public Object JavaDoc getValueAt(int aRow, int aColumn) {
200         Vector JavaDoc row = (Vector JavaDoc)rows.elementAt(aRow);
201         return row.elementAt(aColumn);
202     }
203
204     public String JavaDoc dbRepresentation(int column, Object JavaDoc value) {
205         int type;
206
207         if (value == null) {
208             return "null";
209         }
210
211         try {
212             type = metaData.getColumnType(column+1);
213         }
214         catch (SQLException e) {
215             return value.toString();
216         }
217
218         switch(type) {
219         case Types.INTEGER:
220         case Types.DOUBLE:
221         case Types.FLOAT:
222             return value.toString();
223         case Types.BIT:
224             return ((Boolean JavaDoc)value).booleanValue() ? "1" : "0";
225         case Types.DATE:
226             return value.toString(); // This will need some conversion.
227
default:
228             return "\""+value.toString()+"\"";
229         }
230
231     }
232
233     public void setValueAt(Object JavaDoc value, int row, int column) {
234         try {
235             String JavaDoc tableName = metaData.getTableName(column+1);
236             // Some of the drivers seem buggy, tableName should not be null.
237
if (tableName == null) {
238                 System.out.println("Table name returned null.");
239             }
240             String JavaDoc columnName = getColumnName(column);
241             String JavaDoc query =
242                 "update "+tableName+
243                 " set "+columnName+" = "+dbRepresentation(column, value)+
244                 " where ";
245             // We don't have a model of the schema so we don't know the
246
// primary keys or which columns to lock on. To demonstrate
247
// that editing is possible, we'll just lock on everything.
248
for(int col = 0; col<getColumnCount(); col++) {
249                 String JavaDoc colName = getColumnName(col);
250                 if (colName.equals("")) {
251                     continue;
252                 }
253                 if (col != 0) {
254                     query = query + " and ";
255                 }
256                 query = query + colName +" = "+
257                     dbRepresentation(col, getValueAt(row, col));
258             }
259             System.out.println(query);
260             System.out.println("Not sending update to database");
261             // statement.executeQuery(query);
262
}
263         catch (SQLException e) {
264             // e.printStackTrace();
265
System.err.println("Update failed");
266         }
267         Vector JavaDoc dataRow = (Vector JavaDoc)rows.elementAt(row);
268         dataRow.setElementAt(value, column);
269
270     }
271 }
272
Popular Tags