home *** CD-ROM | disk | FTP | other *** search
/ Chip 1999 July / CHIP-1999-07.iso / software / jdk / jdk121.exe / disk1 / data1.cab / demos / demo / jfc / Table / JDBCAdapter.java < prev    next >
Encoding:
Java Source  |  1999-03-27  |  7.2 KB  |  246 lines

  1. /*
  2.  * @(#)JDBCAdapter.java    1.9 98/08/26
  3.  *
  4.  * Copyright 1997, 1998 by Sun Microsystems, Inc.,
  5.  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
  6.  * All rights reserved.
  7.  *
  8.  * This software is the confidential and proprietary information
  9.  * of Sun Microsystems, Inc. ("Confidential Information").  You
  10.  * shall not disclose such Confidential Information and shall use
  11.  * it only in accordance with the terms of the license agreement
  12.  * you entered into with Sun.
  13.  */
  14.  
  15. /**
  16.  * An adaptor, transforming the JDBC interface to the TableModel interface.
  17.  *
  18.  * @version 1.20 09/25/97
  19.  * @author Philip Milne
  20.  */
  21.  
  22. import java.util.Vector;
  23. import java.sql.*;
  24. import javax.swing.table.AbstractTableModel;
  25. import javax.swing.event.TableModelEvent;
  26.  
  27. public class JDBCAdapter extends AbstractTableModel {
  28.     Connection          connection;
  29.     Statement           statement;
  30.     ResultSet           resultSet;
  31.     String[]            columnNames = {};
  32.     Vector        rows = new Vector();
  33.     ResultSetMetaData   metaData;
  34.  
  35.     public JDBCAdapter(String url, String driverName,
  36.                        String user, String passwd) {
  37.         try {
  38.             Class.forName(driverName);
  39.             System.out.println("Opening db connection");
  40.  
  41.             connection = DriverManager.getConnection(url, user, passwd);
  42.             statement = connection.createStatement();
  43.         }
  44.         catch (ClassNotFoundException ex) {
  45.             System.err.println("Cannot find the database driver classes.");
  46.             System.err.println(ex);
  47.         }
  48.         catch (SQLException ex) {
  49.             System.err.println("Cannot connect to this database.");
  50.             System.err.println(ex);
  51.         }
  52.      }
  53.  
  54.     public void executeQuery(String query) {
  55.         if (connection == null || statement == null) {
  56.             System.err.println("There is no database to execute the query.");
  57.             return;
  58.         }
  59.         try {
  60.             resultSet = statement.executeQuery(query);
  61.             metaData = resultSet.getMetaData();
  62.  
  63.             int numberOfColumns =  metaData.getColumnCount();
  64.             columnNames = new String[numberOfColumns];
  65.             // Get the column names and cache them.
  66.             // Then we can close the connection.
  67.             for(int column = 0; column < numberOfColumns; column++) {
  68.                 columnNames[column] = metaData.getColumnLabel(column+1);
  69.             }
  70.  
  71.             // Get all rows.
  72.             rows = new Vector();
  73.             while (resultSet.next()) {
  74.                 Vector newRow = new Vector();
  75.                 for (int i = 1; i <= getColumnCount(); i++) {
  76.                 newRow.addElement(resultSet.getObject(i));
  77.                 }
  78.                 rows.addElement(newRow);
  79.             }
  80.             //  close(); Need to copy the metaData, bug in jdbc:odbc driver.
  81.             fireTableChanged(null); // Tell the listeners a new table has arrived.
  82.         }
  83.         catch (SQLException ex) {
  84.             System.err.println(ex);
  85.         }
  86.     }
  87.  
  88.     public void close() throws SQLException {
  89.         System.out.println("Closing db connection");
  90.         resultSet.close();
  91.         statement.close();
  92.         connection.close();
  93.     }
  94.  
  95.     protected void finalize() throws Throwable {
  96.         close();
  97.         super.finalize();
  98.     }
  99.  
  100.     //////////////////////////////////////////////////////////////////////////
  101.     //
  102.     //             Implementation of the TableModel Interface
  103.     //
  104.     //////////////////////////////////////////////////////////////////////////
  105.  
  106.     // MetaData
  107.  
  108.     public String getColumnName(int column) {
  109.         if (columnNames[column] != null) {
  110.             return columnNames[column];
  111.         } else {
  112.             return "";
  113.         }
  114.     }
  115.  
  116.     public Class getColumnClass(int column) {
  117.         int type;
  118.         try {
  119.             type = metaData.getColumnType(column+1);
  120.         }
  121.         catch (SQLException e) {
  122.             return super.getColumnClass(column);
  123.         }
  124.  
  125.         switch(type) {
  126.         case Types.CHAR:
  127.         case Types.VARCHAR:
  128.         case Types.LONGVARCHAR:
  129.             return String.class;
  130.  
  131.         case Types.BIT:
  132.             return Boolean.class;
  133.  
  134.         case Types.TINYINT:
  135.         case Types.SMALLINT:
  136.         case Types.INTEGER:
  137.             return Integer.class;
  138.  
  139.         case Types.BIGINT:
  140.             return Long.class;
  141.  
  142.         case Types.FLOAT:
  143.         case Types.DOUBLE:
  144.             return Double.class;
  145.  
  146.         case Types.DATE:
  147.             return java.sql.Date.class;
  148.  
  149.         default:
  150.             return Object.class;
  151.         }
  152.     }
  153.  
  154.     public boolean isCellEditable(int row, int column) {
  155.         try {
  156.             return metaData.isWritable(column+1);
  157.         }
  158.         catch (SQLException e) {
  159.             return false;
  160.         }
  161.     }
  162.  
  163.     public int getColumnCount() {
  164.         return columnNames.length;
  165.     }
  166.  
  167.     // Data methods
  168.  
  169.     public int getRowCount() {
  170.         return rows.size();
  171.     }
  172.  
  173.     public Object getValueAt(int aRow, int aColumn) {
  174.         Vector row = (Vector)rows.elementAt(aRow);
  175.         return row.elementAt(aColumn);
  176.     }
  177.  
  178.     public String dbRepresentation(int column, Object value) {
  179.         int type;
  180.  
  181.         if (value == null) {
  182.             return "null";
  183.         }
  184.  
  185.         try {
  186.             type = metaData.getColumnType(column+1);
  187.         }
  188.         catch (SQLException e) {
  189.             return value.toString();
  190.         }
  191.  
  192.         switch(type) {
  193.         case Types.INTEGER:
  194.         case Types.DOUBLE:
  195.         case Types.FLOAT:
  196.             return value.toString();
  197.         case Types.BIT:
  198.             return ((Boolean)value).booleanValue() ? "1" : "0";
  199.         case Types.DATE:
  200.             return value.toString(); // This will need some conversion.
  201.         default:
  202.             return "\""+value.toString()+"\"";
  203.         }
  204.  
  205.     }
  206.  
  207.     public void setValueAt(Object value, int row, int column) {
  208.         try {
  209.             String tableName = metaData.getTableName(column+1);
  210.             // Some of the drivers seem buggy, tableName should not be null.
  211.             if (tableName == null) {
  212.                 System.out.println("Table name returned null.");
  213.             }
  214.             String columnName = getColumnName(column);
  215.             String query =
  216.                 "update "+tableName+
  217.                 " set "+columnName+" = "+dbRepresentation(column, value)+
  218.                 " where ";
  219.             // We don't have a model of the schema so we don't know the
  220.             // primary keys or which columns to lock on. To demonstrate
  221.             // that editing is possible, we'll just lock on everything.
  222.             for(int col = 0; col<getColumnCount(); col++) {
  223.                 String colName = getColumnName(col);
  224.                 if (colName.equals("")) {
  225.                     continue;
  226.                 }
  227.                 if (col != 0) {
  228.                     query = query + " and ";
  229.                 }
  230.                 query = query + colName +" = "+
  231.                     dbRepresentation(col, getValueAt(row, col));
  232.             }
  233.             System.out.println(query);
  234.             System.out.println("Not sending update to database");
  235.             // statement.executeQuery(query);
  236.         }
  237.         catch (SQLException e) {
  238.             //     e.printStackTrace();
  239.             System.err.println("Update failed");
  240.         }
  241.         Vector dataRow = (Vector)rows.elementAt(row);
  242.         dataRow.setElementAt(value, column);
  243.  
  244.     }
  245. }
  246.