home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / JBuilder8.iso / Solaris / resource / jre / demo / plugin / jfc / TableExample / src / JDBCAdapter.java next >
Encoding:
Java Source  |  2002-09-06  |  8.5 KB  |  271 lines

  1. /*
  2.  * Copyright (c) 2002 Sun Microsystems, Inc. All  Rights Reserved.
  3.  * 
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  * 
  8.  * -Redistributions of source code must retain the above copyright
  9.  *  notice, this list of conditions and the following disclaimer.
  10.  * 
  11.  * -Redistribution in binary form must reproduct the above copyright
  12.  *  notice, this list of conditions and the following disclaimer in
  13.  *  the documentation and/or other materials provided with the distribution.
  14.  * 
  15.  * Neither the name of Sun Microsystems, Inc. or the names of contributors
  16.  * may be used to endorse or promote products derived from this software
  17.  * without specific prior written permission.
  18.  * 
  19.  * This software is provided "AS IS," without a warranty of any kind. ALL
  20.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
  21.  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
  22.  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
  23.  * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
  24.  * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
  25.  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
  26.  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
  27.  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
  28.  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
  29.  * IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  30.  * 
  31.  * You acknowledge that Software is not designed, licensed or intended for
  32.  * use in the design, construction, operation or maintenance of any nuclear
  33.  * facility.
  34.  */
  35.  
  36. /*
  37.  * @(#)JDBCAdapter.java    1.13 02/06/13
  38.  */
  39.  
  40. /**
  41.  * An adaptor, transforming the JDBC interface to the TableModel interface.
  42.  *
  43.  * @version 1.20 09/25/97
  44.  * @author Philip Milne
  45.  */
  46.  
  47. import java.util.Vector;
  48. import java.sql.*;
  49. import javax.swing.table.AbstractTableModel;
  50. import javax.swing.event.TableModelEvent;
  51.  
  52. public class JDBCAdapter extends AbstractTableModel {
  53.     Connection          connection;
  54.     Statement           statement;
  55.     ResultSet           resultSet;
  56.     String[]            columnNames = {};
  57.     Vector        rows = new Vector();
  58.     ResultSetMetaData   metaData;
  59.  
  60.     public JDBCAdapter(String url, String driverName,
  61.                        String user, String passwd) {
  62.         try {
  63.             Class.forName(driverName);
  64.             System.out.println("Opening db connection");
  65.  
  66.             connection = DriverManager.getConnection(url, user, passwd);
  67.             statement = connection.createStatement();
  68.         }
  69.         catch (ClassNotFoundException ex) {
  70.             System.err.println("Cannot find the database driver classes.");
  71.             System.err.println(ex);
  72.         }
  73.         catch (SQLException ex) {
  74.             System.err.println("Cannot connect to this database.");
  75.             System.err.println(ex);
  76.         }
  77.      }
  78.  
  79.     public void executeQuery(String query) {
  80.         if (connection == null || statement == null) {
  81.             System.err.println("There is no database to execute the query.");
  82.             return;
  83.         }
  84.         try {
  85.             resultSet = statement.executeQuery(query);
  86.             metaData = resultSet.getMetaData();
  87.  
  88.             int numberOfColumns =  metaData.getColumnCount();
  89.             columnNames = new String[numberOfColumns];
  90.             // Get the column names and cache them.
  91.             // Then we can close the connection.
  92.             for(int column = 0; column < numberOfColumns; column++) {
  93.                 columnNames[column] = metaData.getColumnLabel(column+1);
  94.             }
  95.  
  96.             // Get all rows.
  97.             rows = new Vector();
  98.             while (resultSet.next()) {
  99.                 Vector newRow = new Vector();
  100.                 for (int i = 1; i <= getColumnCount(); i++) {
  101.                 newRow.addElement(resultSet.getObject(i));
  102.                 }
  103.                 rows.addElement(newRow);
  104.             }
  105.             //  close(); Need to copy the metaData, bug in jdbc:odbc driver.
  106.             fireTableChanged(null); // Tell the listeners a new table has arrived.
  107.         }
  108.         catch (SQLException ex) {
  109.             System.err.println(ex);
  110.         }
  111.     }
  112.  
  113.     public void close() throws SQLException {
  114.         System.out.println("Closing db connection");
  115.         resultSet.close();
  116.         statement.close();
  117.         connection.close();
  118.     }
  119.  
  120.     protected void finalize() throws Throwable {
  121.         close();
  122.         super.finalize();
  123.     }
  124.  
  125.     //////////////////////////////////////////////////////////////////////////
  126.     //
  127.     //             Implementation of the TableModel Interface
  128.     //
  129.     //////////////////////////////////////////////////////////////////////////
  130.  
  131.     // MetaData
  132.  
  133.     public String getColumnName(int column) {
  134.         if (columnNames[column] != null) {
  135.             return columnNames[column];
  136.         } else {
  137.             return "";
  138.         }
  139.     }
  140.  
  141.     public Class getColumnClass(int column) {
  142.         int type;
  143.         try {
  144.             type = metaData.getColumnType(column+1);
  145.         }
  146.         catch (SQLException e) {
  147.             return super.getColumnClass(column);
  148.         }
  149.  
  150.         switch(type) {
  151.         case Types.CHAR:
  152.         case Types.VARCHAR:
  153.         case Types.LONGVARCHAR:
  154.             return String.class;
  155.  
  156.         case Types.BIT:
  157.             return Boolean.class;
  158.  
  159.         case Types.TINYINT:
  160.         case Types.SMALLINT:
  161.         case Types.INTEGER:
  162.             return Integer.class;
  163.  
  164.         case Types.BIGINT:
  165.             return Long.class;
  166.  
  167.         case Types.FLOAT:
  168.         case Types.DOUBLE:
  169.             return Double.class;
  170.  
  171.         case Types.DATE:
  172.             return java.sql.Date.class;
  173.  
  174.         default:
  175.             return Object.class;
  176.         }
  177.     }
  178.  
  179.     public boolean isCellEditable(int row, int column) {
  180.         try {
  181.             return metaData.isWritable(column+1);
  182.         }
  183.         catch (SQLException e) {
  184.             return false;
  185.         }
  186.     }
  187.  
  188.     public int getColumnCount() {
  189.         return columnNames.length;
  190.     }
  191.  
  192.     // Data methods
  193.  
  194.     public int getRowCount() {
  195.         return rows.size();
  196.     }
  197.  
  198.     public Object getValueAt(int aRow, int aColumn) {
  199.         Vector row = (Vector)rows.elementAt(aRow);
  200.         return row.elementAt(aColumn);
  201.     }
  202.  
  203.     public String dbRepresentation(int column, Object value) {
  204.         int type;
  205.  
  206.         if (value == null) {
  207.             return "null";
  208.         }
  209.  
  210.         try {
  211.             type = metaData.getColumnType(column+1);
  212.         }
  213.         catch (SQLException e) {
  214.             return value.toString();
  215.         }
  216.  
  217.         switch(type) {
  218.         case Types.INTEGER:
  219.         case Types.DOUBLE:
  220.         case Types.FLOAT:
  221.             return value.toString();
  222.         case Types.BIT:
  223.             return ((Boolean)value).booleanValue() ? "1" : "0";
  224.         case Types.DATE:
  225.             return value.toString(); // This will need some conversion.
  226.         default:
  227.             return "\""+value.toString()+"\"";
  228.         }
  229.  
  230.     }
  231.  
  232.     public void setValueAt(Object value, int row, int column) {
  233.         try {
  234.             String tableName = metaData.getTableName(column+1);
  235.             // Some of the drivers seem buggy, tableName should not be null.
  236.             if (tableName == null) {
  237.                 System.out.println("Table name returned null.");
  238.             }
  239.             String columnName = getColumnName(column);
  240.             String query =
  241.                 "update "+tableName+
  242.                 " set "+columnName+" = "+dbRepresentation(column, value)+
  243.                 " where ";
  244.             // We don't have a model of the schema so we don't know the
  245.             // primary keys or which columns to lock on. To demonstrate
  246.             // that editing is possible, we'll just lock on everything.
  247.             for(int col = 0; col<getColumnCount(); col++) {
  248.                 String colName = getColumnName(col);
  249.                 if (colName.equals("")) {
  250.                     continue;
  251.                 }
  252.                 if (col != 0) {
  253.                     query = query + " and ";
  254.                 }
  255.                 query = query + colName +" = "+
  256.                     dbRepresentation(col, getValueAt(row, col));
  257.             }
  258.             System.out.println(query);
  259.             System.out.println("Not sending update to database");
  260.             // statement.executeQuery(query);
  261.         }
  262.         catch (SQLException e) {
  263.             //     e.printStackTrace();
  264.             System.err.println("Update failed");
  265.         }
  266.         Vector dataRow = (Vector)rows.elementAt(row);
  267.         dataRow.setElementAt(value, column);
  268.  
  269.     }
  270. }
  271.