Path: blob/master/src/demo/share/jfc/TableExample/JDBCAdapter.java
41149 views
/*1* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6*7* - Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9*10* - Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* - Neither the name of Oracle nor the names of its15* contributors may be used to endorse or promote products derived16* from this software without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS19* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,20* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR21* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR22* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,23* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,24* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29*/3031/*32* This source code is provided to illustrate the usage of a given feature33* or technique and has been deliberately simplified. Additional steps34* required for a production-quality application, such as security checks,35* input validation and proper error handling, might not be present in36* this sample code.37*/38394041import java.sql.Connection;42import java.sql.DriverManager;43import java.sql.ResultSet;44import java.sql.ResultSetMetaData;45import java.sql.SQLException;46import java.sql.Statement;47import java.sql.Types;48import java.util.ArrayList;49import java.util.List;50import javax.swing.table.AbstractTableModel;515253/**54* An adaptor, transforming the JDBC interface to the TableModel interface.55*56* @author Philip Milne57*/58@SuppressWarnings("serial")59public class JDBCAdapter extends AbstractTableModel {6061Connection connection;62Statement statement;63ResultSet resultSet;64String[] columnNames = {};65List<List<Object>> rows = new ArrayList<List<Object>>();66ResultSetMetaData metaData;6768public JDBCAdapter(String url, String driverName,69String user, String passwd) {70try {71Class.forName(driverName);72System.out.println("Opening db connection");7374connection = DriverManager.getConnection(url, user, passwd);75statement = connection.createStatement();76} catch (ClassNotFoundException ex) {77System.err.println("Cannot find the database driver classes.");78System.err.println(ex);79} catch (SQLException ex) {80System.err.println("Cannot connect to this database.");81System.err.println(ex);82}83}8485public void executeQuery(String query) {86if (connection == null || statement == null) {87System.err.println("There is no database to execute the query.");88return;89}90try {91resultSet = statement.executeQuery(query);92metaData = resultSet.getMetaData();9394int numberOfColumns = metaData.getColumnCount();95columnNames = new String[numberOfColumns];96// Get the column names and cache them.97// Then we can close the connection.98for (int column = 0; column < numberOfColumns; column++) {99columnNames[column] = metaData.getColumnLabel(column + 1);100}101102// Get all rows.103rows = new ArrayList<List<Object>>();104while (resultSet.next()) {105List<Object> newRow = new ArrayList<Object>();106for (int i = 1; i <= getColumnCount(); i++) {107newRow.add(resultSet.getObject(i));108}109rows.add(newRow);110}111// close(); Need to copy the metaData, bug in jdbc:odbc driver.112113// Tell the listeners a new table has arrived.114fireTableChanged(null);115} catch (SQLException ex) {116System.err.println(ex);117}118}119120public void close() throws SQLException {121System.out.println("Closing db connection");122resultSet.close();123statement.close();124connection.close();125}126127//////////////////////////////////////////////////////////////////////////128//129// Implementation of the TableModel Interface130//131//////////////////////////////////////////////////////////////////////////132// MetaData133@Override134public String getColumnName(int column) {135if (columnNames[column] != null) {136return columnNames[column];137} else {138return "";139}140}141142@Override143public Class<?> getColumnClass(int column) {144int type;145try {146type = metaData.getColumnType(column + 1);147} catch (SQLException e) {148return super.getColumnClass(column);149}150151switch (type) {152case Types.CHAR:153case Types.VARCHAR:154case Types.LONGVARCHAR:155return String.class;156157case Types.BIT:158return Boolean.class;159160case Types.TINYINT:161case Types.SMALLINT:162case Types.INTEGER:163return Integer.class;164165case Types.BIGINT:166return Long.class;167168case Types.FLOAT:169case Types.DOUBLE:170return Double.class;171172case Types.DATE:173return java.sql.Date.class;174175default:176return Object.class;177}178}179180@Override181public boolean isCellEditable(int row, int column) {182try {183return metaData.isWritable(column + 1);184} catch (SQLException e) {185return false;186}187}188189public int getColumnCount() {190return columnNames.length;191}192193// Data methods194public int getRowCount() {195return rows.size();196}197198public Object getValueAt(int aRow, int aColumn) {199List<Object> row = rows.get(aRow);200return row.get(aColumn);201}202203public String dbRepresentation(int column, Object value) {204int type;205206if (value == null) {207return "null";208}209210try {211type = metaData.getColumnType(column + 1);212} catch (SQLException e) {213return value.toString();214}215216switch (type) {217case Types.INTEGER:218case Types.DOUBLE:219case Types.FLOAT:220return value.toString();221case Types.BIT:222return ((Boolean) value).booleanValue() ? "1" : "0";223case Types.DATE:224return value.toString(); // This will need some conversion.225default:226return "\"" + value.toString() + "\"";227}228229}230231@Override232public void setValueAt(Object value, int row, int column) {233try {234String tableName = metaData.getTableName(column + 1);235// Some of the drivers seem buggy, tableName should not be null.236if (tableName == null) {237System.out.println("Table name returned null.");238}239String columnName = getColumnName(column);240String query =241"update " + tableName + " set " + columnName + " = "242+ dbRepresentation(column, value) + " where ";243// We don't have a model of the schema so we don't know the244// primary keys or which columns to lock on. To demonstrate245// that editing is possible, we'll just lock on everything.246for (int col = 0; col < getColumnCount(); col++) {247String colName = getColumnName(col);248if (colName.equals("")) {249continue;250}251if (col != 0) {252query = query + " and ";253}254query = query + colName + " = " + dbRepresentation(col,255getValueAt(row, col));256}257System.out.println(query);258System.out.println("Not sending update to database");259// statement.executeQuery(query);260} catch (SQLException e) {261// e.printStackTrace();262System.err.println("Update failed");263}264List<Object> dataRow = rows.get(row);265dataRow.set(column, value);266267}268}269270271