Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/demo/jfc/TableExample/JDBCAdapter.java
38829 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@Override128protected void finalize() throws Throwable {129close();130super.finalize();131}132133//////////////////////////////////////////////////////////////////////////134//135// Implementation of the TableModel Interface136//137//////////////////////////////////////////////////////////////////////////138// MetaData139@Override140public String getColumnName(int column) {141if (columnNames[column] != null) {142return columnNames[column];143} else {144return "";145}146}147148@Override149public Class<?> getColumnClass(int column) {150int type;151try {152type = metaData.getColumnType(column + 1);153} catch (SQLException e) {154return super.getColumnClass(column);155}156157switch (type) {158case Types.CHAR:159case Types.VARCHAR:160case Types.LONGVARCHAR:161return String.class;162163case Types.BIT:164return Boolean.class;165166case Types.TINYINT:167case Types.SMALLINT:168case Types.INTEGER:169return Integer.class;170171case Types.BIGINT:172return Long.class;173174case Types.FLOAT:175case Types.DOUBLE:176return Double.class;177178case Types.DATE:179return java.sql.Date.class;180181default:182return Object.class;183}184}185186@Override187public boolean isCellEditable(int row, int column) {188try {189return metaData.isWritable(column + 1);190} catch (SQLException e) {191return false;192}193}194195public int getColumnCount() {196return columnNames.length;197}198199// Data methods200public int getRowCount() {201return rows.size();202}203204public Object getValueAt(int aRow, int aColumn) {205List<Object> row = rows.get(aRow);206return row.get(aColumn);207}208209public String dbRepresentation(int column, Object value) {210int type;211212if (value == null) {213return "null";214}215216try {217type = metaData.getColumnType(column + 1);218} catch (SQLException e) {219return value.toString();220}221222switch (type) {223case Types.INTEGER:224case Types.DOUBLE:225case Types.FLOAT:226return value.toString();227case Types.BIT:228return ((Boolean) value).booleanValue() ? "1" : "0";229case Types.DATE:230return value.toString(); // This will need some conversion.231default:232return "\"" + value.toString() + "\"";233}234235}236237@Override238public void setValueAt(Object value, int row, int column) {239try {240String tableName = metaData.getTableName(column + 1);241// Some of the drivers seem buggy, tableName should not be null.242if (tableName == null) {243System.out.println("Table name returned null.");244}245String columnName = getColumnName(column);246String query =247"update " + tableName + " set " + columnName + " = "248+ dbRepresentation(column, value) + " where ";249// We don't have a model of the schema so we don't know the250// primary keys or which columns to lock on. To demonstrate251// that editing is possible, we'll just lock on everything.252for (int col = 0; col < getColumnCount(); col++) {253String colName = getColumnName(col);254if (colName.equals("")) {255continue;256}257if (col != 0) {258query = query + " and ";259}260query = query + colName + " = " + dbRepresentation(col,261getValueAt(row, col));262}263System.out.println(query);264System.out.println("Not sending update to database");265// statement.executeQuery(query);266} catch (SQLException e) {267// e.printStackTrace();268System.err.println("Update failed");269}270List<Object> dataRow = rows.get(row);271dataRow.set(column, value);272273}274}275276277