/* * HeaderGridModel.java * * Copyright 2000 Eliad Technologies, Inc. All Rights Reserved. * * This software is the proprietary information of Eliad Technologies, Inc. */ package example03; import java.util.*; import java.sql.*; import com.eliad.model.*; /** This class extends the {@link com.eliad.model.GenericGridModel} to provide the initialization of the structures with the data extracted from a database * @author Daniel Rosenblatt * @version 1.0 */ public class HeaderGridModel extends GenericGridModel { private Connection connection_; private Statement statement_; private String query_; private GridModel columnHeaderModel_; /** Creates new DBGridModel * @param url * @param driverName * @param user * @param passwd * @throws ClassNotFoundException * @throws SQLException */ public HeaderGridModel(String url,String driverName) throws ClassNotFoundException, SQLException { this(url,driverName,"",""); } public HeaderGridModel(String url,String driverName,String user,String passwd) throws ClassNotFoundException, SQLException { Class.forName(driverName); connection_ = DriverManager.getConnection(url, user, passwd); statement_ = connection_.createStatement(); } public void setQuery(String query) { if (connection_ == null || statement_ == null) throw new IllegalStateException("There is no database or statement to execute the query."); try { query_ = query; ResultSet resultSet = statement_.executeQuery(query); ResultSetMetaData metaData = resultSet.getMetaData(); final int colCount = metaData.getColumnCount(); final String[] colNames = new String[colCount]; for (int i = 0; i < colCount; i++) colNames[i] = metaData.getColumnName(i+1); columnHeaderModel_ = new AbstractGridModel () { public int getRowCount() { return 1; } public int getColumnCount() { return colCount; } public Object getValueAt(int row, int column) { return colNames[column]; } }; Vector rows = new Vector(); // Get all rows. while (resultSet.next()) { Vector newRow = new Vector(colCount); for (int i = 0; i < colCount; i++) newRow.add(resultSet.getObject(i+1)); rows.add(newRow); } resultSet.close(); setDataVector(rows); } catch (SQLException ex) { System.err.println(ex); } } public String getQuery() { return query_; } public GridModel getColumnHeaderModel() { return columnHeaderModel_; } public void close() throws SQLException { statement_.close(); connection_.close(); } protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } }