Java by API/java.sql/Types

Материал из Java эксперт
Версия от 14:46, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Types.BIGINT

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
/**
 * Print an SQL ResultSet in SQL-import format. TODO: check all escaped
 * characters needed! Test on PGSQL and DB2 at least...
 * 
 * @version $Id: ResultsDecoratorSQL.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
public class Main extends ResultsDecorator {
  Main(ResultsDecoratorPrinter out) {
    super(out);
  }
  public void write(ResultSet rs) throws IOException, SQLException {
    ResultSetMetaData md = rs.getMetaData();
    // This assumes you"re not using a Join!!
    String tableName = md.getTableName(1);
    int cols = md.getColumnCount();
    StringBuffer sb = new StringBuffer("insert into ").append(tableName)
        .append("(");
    for (int i = 1; i <= cols; i++) {
      sb.append(md.getColumnName(i));
      if (i != cols) {
        sb.append(", ");
      }
    }
    sb.append(") values (");
    String insertCommand = sb.toString();
    while (rs.next()) {
      println(insertCommand);
      for (int i = 1; i <= cols; i++) {
        String tmp = rs.getString(i);
        if (rs.wasNull()) {
          print("null");
        } else {
          int type = md.getColumnType(i);
          // Don"t quote numeric types; quote all others for now.
          switch (type) {
          case Types.BIGINT:
          case Types.DECIMAL:
          case Types.DOUBLE:
          case Types.FLOAT:
          case Types.INTEGER:
            print(tmp);
            break;
          default:
            tmp = tmp.replaceAll(""", """");
            print(""" + tmp + """);
          }
        }
        if (i != cols) {
          print(", ");
        }
      }
      println(");");
    }
  }
  void write(int rowCount) throws IOException {
    println("RowCount: " + rowCount);
  }
  /*
   * (non-Javadoc)
   * 
   * @see ResultsDecorator#getName()
   */
  String getName() {
    return "SQL";
  }
}
/**
 * Base class for a series of ResultSet printers.
 * 
 * @version $Id: ResultsDecorator.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
abstract class ResultsDecorator {
  ResultsDecoratorPrinter parent;
  ResultsDecorator(ResultsDecoratorPrinter wr) {
    this.parent = wr;
  }
  /** Print the name of this Decorator"s output format */
  abstract String getName();
  /** Print the contents of a ResultSet */
  abstract void write(ResultSet rs) throws IOException, SQLException;
  /** Print the results of an operation as a Count */
  abstract void write(int rowCount) throws IOException;
  void println(String line) throws IOException {
    parent.println(line);
  }
  void println() throws IOException {
    parent.println();
  }
  void print(String lineSeg) throws IOException {
    parent.print(lineSeg);
  }
}
/**
 * Callback so that ResultsDecorator can call invoker to handle redirections
 * etc.
 * 
 * @version $Id: ResultsDecoratorPrinter.java,v 1.1 2004/03/26 02:39:33 ian Exp $
 */
interface ResultsDecoratorPrinter {
  void print(String line) throws IOException;
  void println(String line) throws IOException;
  void println() throws IOException;
  PrintWriter getPrintWriter();
}





Types.BIT

 
/*
 Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 Use of this software is authorized pursuant to the terms of the license found at
 http://developer.java.sun.ru/berkeley_license.html.
 Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.  
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met: 
 - Redistribution of source code must retain the above copyright notice, 
 this list of conditions and the following disclaimer.
 - Redistribution in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 be used to endorse or promote products derived from this software without
 specific prior written permission.
 This software is provided "AS IS," without a warranty of any kind.  
 ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN")
 AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN
 IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 You acknowledge that this software is not designed, licensed or intended for
 use in the design, construction, operation or maintenance of any nuclear
 facility.

 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
 * Use of this software is authorized pursuant to the terms of the license found at
 * http://developer.java.sun.ru/berkeley_license.html.
 */
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;
    Statement stmt;
    try {
      Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
      System.err.print("ClassNotFoundException: ");
      System.err.println(e.getMessage());
    }
    try {
      con = DriverManager.getConnection(url, "myLogin", "myPassword");
      stmt = con.createStatement();
      Vector dataTypes = getDataTypes(con);
      String tableName;
      String columnName;
      String sqlType;
      String prompt = "Enter the new table name and hit Return: ";
      tableName = getInput(prompt);
      String createTableString = "create table " + tableName + " (";
      String commaAndSpace = ", ";
      boolean firstTime = true;
      while (true) {
        System.out.println("");
        prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
        columnName = getInput(prompt);
        if (firstTime) {
          if (columnName.length() == 0) {
            System.out.print("Need at least one column;");
            System.out.println(" please try again");
            continue;
          } else {
            createTableString += columnName + " ";
            firstTime = false;
          }
        } else if (columnName.length() == 0) {
          break;
        } else {
          createTableString += commaAndSpace + columnName + " ";
        }
        String localTypeName = null;
        String paramString = "";
        while (true) {
          System.out.println("");
          System.out.println("LIST OF TYPES YOU MAY USE:  ");
          boolean firstPrinted = true;
          int length = 0;
          for (int i = 0; i < dataTypes.size(); i++) {
            DataType dataType = (DataType) dataTypes.get(i);
            if (!dataType.needsToBeSet()) {
              if (!firstPrinted)
                System.out.print(commaAndSpace);
              else
                firstPrinted = false;
              System.out.print(dataType.getSQLType());
              length += dataType.getSQLType().length();
              if (length > 50) {
                System.out.println("");
                length = 0;
                firstPrinted = true;
              }
            }
          }
          System.out.println("");
          int index;
          prompt = "Enter a column type " + "from the list and hit Return:  ";
          sqlType = getInput(prompt);
          for (index = 0; index < dataTypes.size(); index++) {
            DataType dataType = (DataType) dataTypes.get(index);
            if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
              break;
            }
          }
          localTypeName = null;
          paramString = "";
          if (index < dataTypes.size()) { // there was a match
            String params;
            DataType dataType = (DataType) dataTypes.get(index);
            params = dataType.getParams();
            localTypeName = dataType.getLocalType();
            if (params != null) {
              prompt = "Enter " + params + ":  ";
              paramString = "(" + getInput(prompt) + ")";
            }
            break;
          } else { // use the name as given
            prompt = "Are you sure?  " + "Enter "y" or "n" and hit Return:  ";
            String check = getInput(prompt) + " ";
            check = check.toLowerCase().substring(0, 1);
            if (check.equals("n"))
              continue;
            else {
              localTypeName = sqlType;
              break;
            }
          }
        }
        createTableString += localTypeName + paramString;
      }
      createTableString += ")";
      System.out.println("");
      System.out.print("Your CREATE TABLE statement as ");
      System.out.println("sent to your DBMS:  ");
      System.out.println(createTableString);
      System.out.println("");
      stmt.executeUpdate(createTableString);
      stmt.close();
      con.close();
    } catch (SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
  }
  private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;
    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)
    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));
    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
      int codeNumber = rs.getInt("DATA_TYPE");
      String dbmsName = rs.getString("TYPE_NAME");
      String createParams = rs.getString("CREATE_PARAMS");
      if (codeNumber == Types.STRUCT && structName == null)
        structName = dbmsName;
      else if (codeNumber == Types.DISTINCT && distinctName == null)
        distinctName = dbmsName;
      else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
        javaName = dbmsName;
      else {
        for (int i = 0; i < dataTypes.size(); i++) {
          // find entry that matches the SQL code,
          // and if local type and params are not already set,
          // set them
          DataType type = (DataType) dataTypes.get(i);
          if (type.getCode() == codeNumber) {
            type.setLocalTypeAndParams(dbmsName, createParams);
          }
        }
      }
    }
    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
      String typeName = null;
      DataType dataType = null;
      if (dbmd.isCatalogAtStart())
        typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
            + rs.getString(3);
      else
        typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
            + rs.getString(1);
      switch (rs.getInt(5)) {
      case Types.STRUCT:
        dataType = new DataType(Types.STRUCT, typeName);
        dataType.setLocalTypeAndParams(structName, null);
        break;
      case Types.DISTINCT:
        dataType = new DataType(Types.DISTINCT, typeName);
        dataType.setLocalTypeAndParams(distinctName, null);
        break;
      case Types.JAVA_OBJECT:
        dataType = new DataType(Types.JAVA_OBJECT, typeName);
        dataType.setLocalTypeAndParams(javaName, null);
        break;
      }
      dataTypes.add(dataType);
    }
    return dataTypes;
  }
  private static String getInput(String prompt) throws SQLException {
    System.out.print(prompt);
    System.out.flush();
    try {
      java.io.BufferedReader bin;
      bin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
      String result = bin.readLine();
      return result;
    } catch (java.io.IOException ex) {
      System.out.println("Caught java.io.IOException:");
      System.out.println(ex.getMessage());
      return "";
    }
  }
}
class DataType {
  private int code;
  private String SQLType;
  private String localType = null;
  private String params = null;
  private boolean needsSetting = true;
  public DataType(int code, String SQLType) {
    this.code = code;
    this.SQLType = SQLType;
  }
  public boolean needsToBeSet() {
    return needsSetting;
  }
  public int getCode() {
    return code;
  }
  public String getSQLType() {
    return SQLType;
  }
  public String getLocalType() {
    return localType;
  }
  public String getParams() {
    return params;
  }
  public void setLocalTypeAndParams(String local, String p) {
    if (needsSetting) {
      localType = local;
      params = p;
      needsSetting = false;
    }
  }
}





Types.BLOB

 
/*
 Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 Use of this software is authorized pursuant to the terms of the license found at
 http://developer.java.sun.ru/berkeley_license.html.
 Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.  
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met: 
 - Redistribution of source code must retain the above copyright notice, 
 this list of conditions and the following disclaimer.
 - Redistribution in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 be used to endorse or promote products derived from this software without
 specific prior written permission.
 This software is provided "AS IS," without a warranty of any kind.  
 ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN")
 AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN
 IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 You acknowledge that this software is not designed, licensed or intended for
 use in the design, construction, operation or maintenance of any nuclear
 facility.

 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
 * Use of this software is authorized pursuant to the terms of the license found at
 * http://developer.java.sun.ru/berkeley_license.html.
 */
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;
    Statement stmt;
    try {
      Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
      System.err.print("ClassNotFoundException: ");
      System.err.println(e.getMessage());
    }
    try {
      con = DriverManager.getConnection(url, "myLogin", "myPassword");
      stmt = con.createStatement();
      Vector dataTypes = getDataTypes(con);
      String tableName;
      String columnName;
      String sqlType;
      String prompt = "Enter the new table name and hit Return: ";
      tableName = getInput(prompt);
      String createTableString = "create table " + tableName + " (";
      String commaAndSpace = ", ";
      boolean firstTime = true;
      while (true) {
        System.out.println("");
        prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
        columnName = getInput(prompt);
        if (firstTime) {
          if (columnName.length() == 0) {
            System.out.print("Need at least one column;");
            System.out.println(" please try again");
            continue;
          } else {
            createTableString += columnName + " ";
            firstTime = false;
          }
        } else if (columnName.length() == 0) {
          break;
        } else {
          createTableString += commaAndSpace + columnName + " ";
        }
        String localTypeName = null;
        String paramString = "";
        while (true) {
          System.out.println("");
          System.out.println("LIST OF TYPES YOU MAY USE:  ");
          boolean firstPrinted = true;
          int length = 0;
          for (int i = 0; i < dataTypes.size(); i++) {
            DataType dataType = (DataType) dataTypes.get(i);
            if (!dataType.needsToBeSet()) {
              if (!firstPrinted)
                System.out.print(commaAndSpace);
              else
                firstPrinted = false;
              System.out.print(dataType.getSQLType());
              length += dataType.getSQLType().length();
              if (length > 50) {
                System.out.println("");
                length = 0;
                firstPrinted = true;
              }
            }
          }
          System.out.println("");
          int index;
          prompt = "Enter a column type " + "from the list and hit Return:  ";
          sqlType = getInput(prompt);
          for (index = 0; index < dataTypes.size(); index++) {
            DataType dataType = (DataType) dataTypes.get(index);
            if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
              break;
            }
          }
          localTypeName = null;
          paramString = "";
          if (index < dataTypes.size()) { // there was a match
            String params;
            DataType dataType = (DataType) dataTypes.get(index);
            params = dataType.getParams();
            localTypeName = dataType.getLocalType();
            if (params != null) {
              prompt = "Enter " + params + ":  ";
              paramString = "(" + getInput(prompt) + ")";
            }
            break;
          } else { // use the name as given
            prompt = "Are you sure?  " + "Enter "y" or "n" and hit Return:  ";
            String check = getInput(prompt) + " ";
            check = check.toLowerCase().substring(0, 1);
            if (check.equals("n"))
              continue;
            else {
              localTypeName = sqlType;
              break;
            }
          }
        }
        createTableString += localTypeName + paramString;
      }
      createTableString += ")";
      System.out.println("");
      System.out.print("Your CREATE TABLE statement as ");
      System.out.println("sent to your DBMS:  ");
      System.out.println(createTableString);
      System.out.println("");
      stmt.executeUpdate(createTableString);
      stmt.close();
      con.close();
    } catch (SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
  }
  private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;
    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)
    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));
    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
      int codeNumber = rs.getInt("DATA_TYPE");
      String dbmsName = rs.getString("TYPE_NAME");
      String createParams = rs.getString("CREATE_PARAMS");
      if (codeNumber == Types.STRUCT && structName == null)
        structName = dbmsName;
      else if (codeNumber == Types.DISTINCT && distinctName == null)
        distinctName = dbmsName;
      else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
        javaName = dbmsName;
      else {
        for (int i = 0; i < dataTypes.size(); i++) {
          // find entry that matches the SQL code,
          // and if local type and params are not already set,
          // set them
          DataType type = (DataType) dataTypes.get(i);
          if (type.getCode() == codeNumber) {
            type.setLocalTypeAndParams(dbmsName, createParams);
          }
        }
      }
    }
    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
      String typeName = null;
      DataType dataType = null;
      if (dbmd.isCatalogAtStart())
        typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
            + rs.getString(3);
      else
        typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
            + rs.getString(1);
      switch (rs.getInt(5)) {
      case Types.STRUCT:
        dataType = new DataType(Types.STRUCT, typeName);
        dataType.setLocalTypeAndParams(structName, null);
        break;
      case Types.DISTINCT:
        dataType = new DataType(Types.DISTINCT, typeName);
        dataType.setLocalTypeAndParams(distinctName, null);
        break;
      case Types.JAVA_OBJECT:
        dataType = new DataType(Types.JAVA_OBJECT, typeName);
        dataType.setLocalTypeAndParams(javaName, null);
        break;
      }
      dataTypes.add(dataType);
    }
    return dataTypes;
  }
  private static String getInput(String prompt) throws SQLException {
    System.out.print(prompt);
    System.out.flush();
    try {
      java.io.BufferedReader bin;
      bin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
      String result = bin.readLine();
      return result;
    } catch (java.io.IOException ex) {
      System.out.println("Caught java.io.IOException:");
      System.out.println(ex.getMessage());
      return "";
    }
  }
}
class DataType {
  private int code;
  private String SQLType;
  private String localType = null;
  private String params = null;
  private boolean needsSetting = true;
  public DataType(int code, String SQLType) {
    this.code = code;
    this.SQLType = SQLType;
  }
  public boolean needsToBeSet() {
    return needsSetting;
  }
  public int getCode() {
    return code;
  }
  public String getSQLType() {
    return SQLType;
  }
  public String getLocalType() {
    return localType;
  }
  public String getParams() {
    return params;
  }
  public void setLocalTypeAndParams(String local, String p) {
    if (needsSetting) {
      localType = local;
      params = p;
      needsSetting = false;
    }
  }
}





Types.CLOB

 
/*
 Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 Use of this software is authorized pursuant to the terms of the license found at
 http://developer.java.sun.ru/berkeley_license.html.
 Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.  
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met: 
 - Redistribution of source code must retain the above copyright notice, 
 this list of conditions and the following disclaimer.
 - Redistribution in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 be used to endorse or promote products derived from this software without
 specific prior written permission.
 This software is provided "AS IS," without a warranty of any kind.  
 ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN")
 AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN
 IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 You acknowledge that this software is not designed, licensed or intended for
 use in the design, construction, operation or maintenance of any nuclear
 facility.

 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
 * Use of this software is authorized pursuant to the terms of the license found at
 * http://developer.java.sun.ru/berkeley_license.html.
 */
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;
    Statement stmt;
    try {
      Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
      System.err.print("ClassNotFoundException: ");
      System.err.println(e.getMessage());
    }
    try {
      con = DriverManager.getConnection(url, "myLogin", "myPassword");
      stmt = con.createStatement();
      Vector dataTypes = getDataTypes(con);
      String tableName;
      String columnName;
      String sqlType;
      String prompt = "Enter the new table name and hit Return: ";
      tableName = getInput(prompt);
      String createTableString = "create table " + tableName + " (";
      String commaAndSpace = ", ";
      boolean firstTime = true;
      while (true) {
        System.out.println("");
        prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
        columnName = getInput(prompt);
        if (firstTime) {
          if (columnName.length() == 0) {
            System.out.print("Need at least one column;");
            System.out.println(" please try again");
            continue;
          } else {
            createTableString += columnName + " ";
            firstTime = false;
          }
        } else if (columnName.length() == 0) {
          break;
        } else {
          createTableString += commaAndSpace + columnName + " ";
        }
        String localTypeName = null;
        String paramString = "";
        while (true) {
          System.out.println("");
          System.out.println("LIST OF TYPES YOU MAY USE:  ");
          boolean firstPrinted = true;
          int length = 0;
          for (int i = 0; i < dataTypes.size(); i++) {
            DataType dataType = (DataType) dataTypes.get(i);
            if (!dataType.needsToBeSet()) {
              if (!firstPrinted)
                System.out.print(commaAndSpace);
              else
                firstPrinted = false;
              System.out.print(dataType.getSQLType());
              length += dataType.getSQLType().length();
              if (length > 50) {
                System.out.println("");
                length = 0;
                firstPrinted = true;
              }
            }
          }
          System.out.println("");
          int index;
          prompt = "Enter a column type " + "from the list and hit Return:  ";
          sqlType = getInput(prompt);
          for (index = 0; index < dataTypes.size(); index++) {
            DataType dataType = (DataType) dataTypes.get(index);
            if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
              break;
            }
          }
          localTypeName = null;
          paramString = "";
          if (index < dataTypes.size()) { // there was a match
            String params;
            DataType dataType = (DataType) dataTypes.get(index);
            params = dataType.getParams();
            localTypeName = dataType.getLocalType();
            if (params != null) {
              prompt = "Enter " + params + ":  ";
              paramString = "(" + getInput(prompt) + ")";
            }
            break;
          } else { // use the name as given
            prompt = "Are you sure?  " + "Enter "y" or "n" and hit Return:  ";
            String check = getInput(prompt) + " ";
            check = check.toLowerCase().substring(0, 1);
            if (check.equals("n"))
              continue;
            else {
              localTypeName = sqlType;
              break;
            }
          }
        }
        createTableString += localTypeName + paramString;
      }
      createTableString += ")";
      System.out.println("");
      System.out.print("Your CREATE TABLE statement as ");
      System.out.println("sent to your DBMS:  ");
      System.out.println(createTableString);
      System.out.println("");
      stmt.executeUpdate(createTableString);
      stmt.close();
      con.close();
    } catch (SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
  }
  private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;
    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)
    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));
    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
      int codeNumber = rs.getInt("DATA_TYPE");
      String dbmsName = rs.getString("TYPE_NAME");
      String createParams = rs.getString("CREATE_PARAMS");
      if (codeNumber == Types.STRUCT && structName == null)
        structName = dbmsName;
      else if (codeNumber == Types.DISTINCT && distinctName == null)
        distinctName = dbmsName;
      else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
        javaName = dbmsName;
      else {
        for (int i = 0; i < dataTypes.size(); i++) {
          // find entry that matches the SQL code,
          // and if local type and params are not already set,
          // set them
          DataType type = (DataType) dataTypes.get(i);
          if (type.getCode() == codeNumber) {
            type.setLocalTypeAndParams(dbmsName, createParams);
          }
        }
      }
    }
    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
      String typeName = null;
      DataType dataType = null;
      if (dbmd.isCatalogAtStart())
        typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
            + rs.getString(3);
      else
        typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
            + rs.getString(1);
      switch (rs.getInt(5)) {
      case Types.STRUCT:
        dataType = new DataType(Types.STRUCT, typeName);
        dataType.setLocalTypeAndParams(structName, null);
        break;
      case Types.DISTINCT:
        dataType = new DataType(Types.DISTINCT, typeName);
        dataType.setLocalTypeAndParams(distinctName, null);
        break;
      case Types.JAVA_OBJECT:
        dataType = new DataType(Types.JAVA_OBJECT, typeName);
        dataType.setLocalTypeAndParams(javaName, null);
        break;
      }
      dataTypes.add(dataType);
    }
    return dataTypes;
  }
  private static String getInput(String prompt) throws SQLException {
    System.out.print(prompt);
    System.out.flush();
    try {
      java.io.BufferedReader bin;
      bin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
      String result = bin.readLine();
      return result;
    } catch (java.io.IOException ex) {
      System.out.println("Caught java.io.IOException:");
      System.out.println(ex.getMessage());
      return "";
    }
  }
}
class DataType {
  private int code;
  private String SQLType;
  private String localType = null;
  private String params = null;
  private boolean needsSetting = true;
  public DataType(int code, String SQLType) {
    this.code = code;
    this.SQLType = SQLType;
  }
  public boolean needsToBeSet() {
    return needsSetting;
  }
  public int getCode() {
    return code;
  }
  public String getSQLType() {
    return SQLType;
  }
  public String getLocalType() {
    return localType;
  }
  public String getParams() {
    return params;
  }
  public void setLocalTypeAndParams(String local, String p) {
    if (needsSetting) {
      localType = local;
      params = p;
      needsSetting = false;
    }
  }
}





Types.DATE

 
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
  public static void main(String[] args) throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    Class.forName(driver).newInstance();
    String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    Connection conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
    printColumnInfo(rs);
    printColumnNames(rs);
    processRs(rs);
    rs = stmt.executeQuery("SELECT * FROM Location");
    printColumnInfo(rs);
    printColumnNames(rs);
    processRs(rs);
    conn.close();
  }
  public static void processRs(ResultSet rs) throws SQLException {
    ResultSetMetaData rmd = rs.getMetaData();
    while (rs.next()) {
      for (int col = 1; col <= rmd.getColumnCount(); col++)
        getData(rs, rmd.getColumnType(col), col);
    }
  }
  public static void printColumnNames(ResultSet rs) throws SQLException {
    ResultSetMetaData rmd = rs.getMetaData();
    for (int col = 1; col <= rmd.getColumnCount(); col++)
      System.out.println(rmd.getColumnName(col) + " ");
  }
  public static void getData(ResultSet rs, int type, int colIdx) throws SQLException {
    switch (type) {
    case java.sql.Types.CHAR:
    case java.sql.Types.VARCHAR:
      System.out.println(rs.getString(colIdx));
      break;
    case java.sql.Types.INTEGER:
      int i = rs.getInt(colIdx);
      System.out.println(i);
      break;
    case java.sql.Types.NUMERIC:
      BigDecimal bd = rs.getBigDecimal(colIdx);
      System.out.println(bd.toString());
      break;
    case java.sql.Types.TIMESTAMP:
    case java.sql.Types.DATE:
      java.sql.Date d = rs.getDate(colIdx);
      System.out.println(d.toString());
      break;
    }
  }
  public static void printColumnInfo(ResultSet rs) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();
    for (int colIdx = 1; colIdx <= cols; colIdx++) {
      String name = rsmd.getColumnName(colIdx);
      int type = rsmd.getColumnType(colIdx);
      String typeName = rsmd.getColumnTypeName(colIdx);
      System.out.println(name + ", " + type + ", " + typeName);
    }
  }
}





Types.DECIMAL

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
/**
 * Print an SQL ResultSet in SQL-import format. TODO: check all escaped
 * characters needed! Test on PGSQL and DB2 at least...
 * 
 * @version $Id: ResultsDecoratorSQL.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
public class Main extends ResultsDecorator {
  Main(ResultsDecoratorPrinter out) {
    super(out);
  }
  public void write(ResultSet rs) throws IOException, SQLException {
    ResultSetMetaData md = rs.getMetaData();
    // This assumes you"re not using a Join!!
    String tableName = md.getTableName(1);
    int cols = md.getColumnCount();
    StringBuffer sb = new StringBuffer("insert into ").append(tableName)
        .append("(");
    for (int i = 1; i <= cols; i++) {
      sb.append(md.getColumnName(i));
      if (i != cols) {
        sb.append(", ");
      }
    }
    sb.append(") values (");
    String insertCommand = sb.toString();
    while (rs.next()) {
      println(insertCommand);
      for (int i = 1; i <= cols; i++) {
        String tmp = rs.getString(i);
        if (rs.wasNull()) {
          print("null");
        } else {
          int type = md.getColumnType(i);
          // Don"t quote numeric types; quote all others for now.
          switch (type) {
          case Types.BIGINT:
          case Types.DECIMAL:
          case Types.DOUBLE:
          case Types.FLOAT:
          case Types.INTEGER:
            print(tmp);
            break;
          default:
            tmp = tmp.replaceAll(""", """");
            print(""" + tmp + """);
          }
        }
        if (i != cols) {
          print(", ");
        }
      }
      println(");");
    }
  }
  void write(int rowCount) throws IOException {
    println("RowCount: " + rowCount);
  }
  /*
   * (non-Javadoc)
   * 
   * @see ResultsDecorator#getName()
   */
  String getName() {
    return "SQL";
  }
}
/**
 * Base class for a series of ResultSet printers.
 * 
 * @version $Id: ResultsDecorator.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
abstract class ResultsDecorator {
  ResultsDecoratorPrinter parent;
  ResultsDecorator(ResultsDecoratorPrinter wr) {
    this.parent = wr;
  }
  /** Print the name of this Decorator"s output format */
  abstract String getName();
  /** Print the contents of a ResultSet */
  abstract void write(ResultSet rs) throws IOException, SQLException;
  /** Print the results of an operation as a Count */
  abstract void write(int rowCount) throws IOException;
  void println(String line) throws IOException {
    parent.println(line);
  }
  void println() throws IOException {
    parent.println();
  }
  void print(String lineSeg) throws IOException {
    parent.print(lineSeg);
  }
}
/**
 * Callback so that ResultsDecorator can call invoker to handle redirections
 * etc.
 * 
 * @version $Id: ResultsDecoratorPrinter.java,v 1.1 2004/03/26 02:39:33 ian Exp $
 */
interface ResultsDecoratorPrinter {
  void print(String line) throws IOException;
  void println(String line) throws IOException;
  void println() throws IOException;
  PrintWriter getPrintWriter();
}





Types.DOUBLE

 

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
/**
 * Print an SQL ResultSet in SQL-import format. TODO: check all escaped
 * characters needed! Test on PGSQL and DB2 at least...
 * 
 * @version $Id: ResultsDecoratorSQL.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
public class Main extends ResultsDecorator {
  Main(ResultsDecoratorPrinter out) {
    super(out);
  }
  public void write(ResultSet rs) throws IOException, SQLException {
    ResultSetMetaData md = rs.getMetaData();
    // This assumes you"re not using a Join!!
    String tableName = md.getTableName(1);
    int cols = md.getColumnCount();
    StringBuffer sb = new StringBuffer("insert into ").append(tableName)
        .append("(");
    for (int i = 1; i <= cols; i++) {
      sb.append(md.getColumnName(i));
      if (i != cols) {
        sb.append(", ");
      }
    }
    sb.append(") values (");
    String insertCommand = sb.toString();
    while (rs.next()) {
      println(insertCommand);
      for (int i = 1; i <= cols; i++) {
        String tmp = rs.getString(i);
        if (rs.wasNull()) {
          print("null");
        } else {
          int type = md.getColumnType(i);
          // Don"t quote numeric types; quote all others for now.
          switch (type) {
          case Types.BIGINT:
          case Types.DECIMAL:
          case Types.DOUBLE:
          case Types.FLOAT:
          case Types.INTEGER:
            print(tmp);
            break;
          default:
            tmp = tmp.replaceAll(""", """");
            print(""" + tmp + """);
          }
        }
        if (i != cols) {
          print(", ");
        }
      }
      println(");");
    }
  }
  void write(int rowCount) throws IOException {
    println("RowCount: " + rowCount);
  }
  /*
   * (non-Javadoc)
   * 
   * @see ResultsDecorator#getName()
   */
  String getName() {
    return "SQL";
  }
}
/**
 * Base class for a series of ResultSet printers.
 * 
 * @version $Id: ResultsDecorator.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
abstract class ResultsDecorator {
  ResultsDecoratorPrinter parent;
  ResultsDecorator(ResultsDecoratorPrinter wr) {
    this.parent = wr;
  }
  /** Print the name of this Decorator"s output format */
  abstract String getName();
  /** Print the contents of a ResultSet */
  abstract void write(ResultSet rs) throws IOException, SQLException;
  /** Print the results of an operation as a Count */
  abstract void write(int rowCount) throws IOException;
  void println(String line) throws IOException {
    parent.println(line);
  }
  void println() throws IOException {
    parent.println();
  }
  void print(String lineSeg) throws IOException {
    parent.print(lineSeg);
  }
}
/**
 * Callback so that ResultsDecorator can call invoker to handle redirections
 * etc.
 * 
 * @version $Id: ResultsDecoratorPrinter.java,v 1.1 2004/03/26 02:39:33 ian Exp $
 */
interface ResultsDecoratorPrinter {
  void print(String line) throws IOException;
  void println(String line) throws IOException;
  void println() throws IOException;
  PrintWriter getPrintWriter();
}





Types.FLOAT

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
/**
 * Print an SQL ResultSet in SQL-import format. TODO: check all escaped
 * characters needed! Test on PGSQL and DB2 at least...
 * 
 * @version $Id: ResultsDecoratorSQL.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
public class Main extends ResultsDecorator {
  Main(ResultsDecoratorPrinter out) {
    super(out);
  }
  public void write(ResultSet rs) throws IOException, SQLException {
    ResultSetMetaData md = rs.getMetaData();
    // This assumes you"re not using a Join!!
    String tableName = md.getTableName(1);
    int cols = md.getColumnCount();
    StringBuffer sb = new StringBuffer("insert into ").append(tableName)
        .append("(");
    for (int i = 1; i <= cols; i++) {
      sb.append(md.getColumnName(i));
      if (i != cols) {
        sb.append(", ");
      }
    }
    sb.append(") values (");
    String insertCommand = sb.toString();
    while (rs.next()) {
      println(insertCommand);
      for (int i = 1; i <= cols; i++) {
        String tmp = rs.getString(i);
        if (rs.wasNull()) {
          print("null");
        } else {
          int type = md.getColumnType(i);
          // Don"t quote numeric types; quote all others for now.
          switch (type) {
          case Types.BIGINT:
          case Types.DECIMAL:
          case Types.DOUBLE:
          case Types.FLOAT:
          case Types.INTEGER:
            print(tmp);
            break;
          default:
            tmp = tmp.replaceAll(""", """");
            print(""" + tmp + """);
          }
        }
        if (i != cols) {
          print(", ");
        }
      }
      println(");");
    }
  }
  void write(int rowCount) throws IOException {
    println("RowCount: " + rowCount);
  }
  /*
   * (non-Javadoc)
   * 
   * @see ResultsDecorator#getName()
   */
  String getName() {
    return "SQL";
  }
}
/**
 * Base class for a series of ResultSet printers.
 * 
 * @version $Id: ResultsDecorator.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
abstract class ResultsDecorator {
  ResultsDecoratorPrinter parent;
  ResultsDecorator(ResultsDecoratorPrinter wr) {
    this.parent = wr;
  }
  /** Print the name of this Decorator"s output format */
  abstract String getName();
  /** Print the contents of a ResultSet */
  abstract void write(ResultSet rs) throws IOException, SQLException;
  /** Print the results of an operation as a Count */
  abstract void write(int rowCount) throws IOException;
  void println(String line) throws IOException {
    parent.println(line);
  }
  void println() throws IOException {
    parent.println();
  }
  void print(String lineSeg) throws IOException {
    parent.print(lineSeg);
  }
}
/**
 * Callback so that ResultsDecorator can call invoker to handle redirections
 * etc.
 * 
 * @version $Id: ResultsDecoratorPrinter.java,v 1.1 2004/03/26 02:39:33 ian Exp $
 */
interface ResultsDecoratorPrinter {
  void print(String line) throws IOException;
  void println(String line) throws IOException;
  void println() throws IOException;
  PrintWriter getPrintWriter();
}





Types.INTEGER

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
/**
 * Print an SQL ResultSet in SQL-import format. TODO: check all escaped
 * characters needed! Test on PGSQL and DB2 at least...
 * 
 * @version $Id: ResultsDecoratorSQL.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
public class Main extends ResultsDecorator {
  Main(ResultsDecoratorPrinter out) {
    super(out);
  }
  public void write(ResultSet rs) throws IOException, SQLException {
    ResultSetMetaData md = rs.getMetaData();
    // This assumes you"re not using a Join!!
    String tableName = md.getTableName(1);
    int cols = md.getColumnCount();
    StringBuffer sb = new StringBuffer("insert into ").append(tableName)
        .append("(");
    for (int i = 1; i <= cols; i++) {
      sb.append(md.getColumnName(i));
      if (i != cols) {
        sb.append(", ");
      }
    }
    sb.append(") values (");
    String insertCommand = sb.toString();
    while (rs.next()) {
      println(insertCommand);
      for (int i = 1; i <= cols; i++) {
        String tmp = rs.getString(i);
        if (rs.wasNull()) {
          print("null");
        } else {
          int type = md.getColumnType(i);
          // Don"t quote numeric types; quote all others for now.
          switch (type) {
          case Types.BIGINT:
          case Types.DECIMAL:
          case Types.DOUBLE:
          case Types.FLOAT:
          case Types.INTEGER:
            print(tmp);
            break;
          default:
            tmp = tmp.replaceAll(""", """");
            print(""" + tmp + """);
          }
        }
        if (i != cols) {
          print(", ");
        }
      }
      println(");");
    }
  }
  void write(int rowCount) throws IOException {
    println("RowCount: " + rowCount);
  }
  /*
   * (non-Javadoc)
   * 
   * @see ResultsDecorator#getName()
   */
  String getName() {
    return "SQL";
  }
}
/**
 * Base class for a series of ResultSet printers.
 * 
 * @version $Id: ResultsDecorator.java,v 1.2 2004/03/26 02:39:33 ian Exp $
 */
abstract class ResultsDecorator {
  ResultsDecoratorPrinter parent;
  ResultsDecorator(ResultsDecoratorPrinter wr) {
    this.parent = wr;
  }
  /** Print the name of this Decorator"s output format */
  abstract String getName();
  /** Print the contents of a ResultSet */
  abstract void write(ResultSet rs) throws IOException, SQLException;
  /** Print the results of an operation as a Count */
  abstract void write(int rowCount) throws IOException;
  void println(String line) throws IOException {
    parent.println(line);
  }
  void println() throws IOException {
    parent.println();
  }
  void print(String lineSeg) throws IOException {
    parent.print(lineSeg);
  }
}
/**
 * Callback so that ResultsDecorator can call invoker to handle redirections
 * etc.
 * 
 * @version $Id: ResultsDecoratorPrinter.java,v 1.1 2004/03/26 02:39:33 ian Exp $
 */
interface ResultsDecoratorPrinter {
  void print(String line) throws IOException;
  void println(String line) throws IOException;
  void println() throws IOException;
  PrintWriter getPrintWriter();
}





Types.LONGVARBINARY

 
/*
 Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 Use of this software is authorized pursuant to the terms of the license found at
 http://developer.java.sun.ru/berkeley_license.html.
 Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.  
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met: 
 - Redistribution of source code must retain the above copyright notice, 
 this list of conditions and the following disclaimer.
 - Redistribution in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 be used to endorse or promote products derived from this software without
 specific prior written permission.
 This software is provided "AS IS," without a warranty of any kind.  
 ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN")
 AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN
 IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 You acknowledge that this software is not designed, licensed or intended for
 use in the design, construction, operation or maintenance of any nuclear
 facility.

 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
 * Use of this software is authorized pursuant to the terms of the license found at
 * http://developer.java.sun.ru/berkeley_license.html.
 */
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;
    Statement stmt;
    try {
      Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
      System.err.print("ClassNotFoundException: ");
      System.err.println(e.getMessage());
    }
    try {
      con = DriverManager.getConnection(url, "myLogin", "myPassword");
      stmt = con.createStatement();
      Vector dataTypes = getDataTypes(con);
      String tableName;
      String columnName;
      String sqlType;
      String prompt = "Enter the new table name and hit Return: ";
      tableName = getInput(prompt);
      String createTableString = "create table " + tableName + " (";
      String commaAndSpace = ", ";
      boolean firstTime = true;
      while (true) {
        System.out.println("");
        prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
        columnName = getInput(prompt);
        if (firstTime) {
          if (columnName.length() == 0) {
            System.out.print("Need at least one column;");
            System.out.println(" please try again");
            continue;
          } else {
            createTableString += columnName + " ";
            firstTime = false;
          }
        } else if (columnName.length() == 0) {
          break;
        } else {
          createTableString += commaAndSpace + columnName + " ";
        }
        String localTypeName = null;
        String paramString = "";
        while (true) {
          System.out.println("");
          System.out.println("LIST OF TYPES YOU MAY USE:  ");
          boolean firstPrinted = true;
          int length = 0;
          for (int i = 0; i < dataTypes.size(); i++) {
            DataType dataType = (DataType) dataTypes.get(i);
            if (!dataType.needsToBeSet()) {
              if (!firstPrinted)
                System.out.print(commaAndSpace);
              else
                firstPrinted = false;
              System.out.print(dataType.getSQLType());
              length += dataType.getSQLType().length();
              if (length > 50) {
                System.out.println("");
                length = 0;
                firstPrinted = true;
              }
            }
          }
          System.out.println("");
          int index;
          prompt = "Enter a column type " + "from the list and hit Return:  ";
          sqlType = getInput(prompt);
          for (index = 0; index < dataTypes.size(); index++) {
            DataType dataType = (DataType) dataTypes.get(index);
            if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
              break;
            }
          }
          localTypeName = null;
          paramString = "";
          if (index < dataTypes.size()) { // there was a match
            String params;
            DataType dataType = (DataType) dataTypes.get(index);
            params = dataType.getParams();
            localTypeName = dataType.getLocalType();
            if (params != null) {
              prompt = "Enter " + params + ":  ";
              paramString = "(" + getInput(prompt) + ")";
            }
            break;
          } else { // use the name as given
            prompt = "Are you sure?  " + "Enter "y" or "n" and hit Return:  ";
            String check = getInput(prompt) + " ";
            check = check.toLowerCase().substring(0, 1);
            if (check.equals("n"))
              continue;
            else {
              localTypeName = sqlType;
              break;
            }
          }
        }
        createTableString += localTypeName + paramString;
      }
      createTableString += ")";
      System.out.println("");
      System.out.print("Your CREATE TABLE statement as ");
      System.out.println("sent to your DBMS:  ");
      System.out.println(createTableString);
      System.out.println("");
      stmt.executeUpdate(createTableString);
      stmt.close();
      con.close();
    } catch (SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
  }
  private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;
    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)
    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));
    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
      int codeNumber = rs.getInt("DATA_TYPE");
      String dbmsName = rs.getString("TYPE_NAME");
      String createParams = rs.getString("CREATE_PARAMS");
      if (codeNumber == Types.STRUCT && structName == null)
        structName = dbmsName;
      else if (codeNumber == Types.DISTINCT && distinctName == null)
        distinctName = dbmsName;
      else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
        javaName = dbmsName;
      else {
        for (int i = 0; i < dataTypes.size(); i++) {
          // find entry that matches the SQL code,
          // and if local type and params are not already set,
          // set them
          DataType type = (DataType) dataTypes.get(i);
          if (type.getCode() == codeNumber) {
            type.setLocalTypeAndParams(dbmsName, createParams);
          }
        }
      }
    }
    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
      String typeName = null;
      DataType dataType = null;
      if (dbmd.isCatalogAtStart())
        typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
            + rs.getString(3);
      else
        typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
            + rs.getString(1);
      switch (rs.getInt(5)) {
      case Types.STRUCT:
        dataType = new DataType(Types.STRUCT, typeName);
        dataType.setLocalTypeAndParams(structName, null);
        break;
      case Types.DISTINCT:
        dataType = new DataType(Types.DISTINCT, typeName);
        dataType.setLocalTypeAndParams(distinctName, null);
        break;
      case Types.JAVA_OBJECT:
        dataType = new DataType(Types.JAVA_OBJECT, typeName);
        dataType.setLocalTypeAndParams(javaName, null);
        break;
      }
      dataTypes.add(dataType);
    }
    return dataTypes;
  }
  private static String getInput(String prompt) throws SQLException {
    System.out.print(prompt);
    System.out.flush();
    try {
      java.io.BufferedReader bin;
      bin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
      String result = bin.readLine();
      return result;
    } catch (java.io.IOException ex) {
      System.out.println("Caught java.io.IOException:");
      System.out.println(ex.getMessage());
      return "";
    }
  }
}
class DataType {
  private int code;
  private String SQLType;
  private String localType = null;
  private String params = null;
  private boolean needsSetting = true;
  public DataType(int code, String SQLType) {
    this.code = code;
    this.SQLType = SQLType;
  }
  public boolean needsToBeSet() {
    return needsSetting;
  }
  public int getCode() {
    return code;
  }
  public String getSQLType() {
    return SQLType;
  }
  public String getLocalType() {
    return localType;
  }
  public String getParams() {
    return params;
  }
  public void setLocalTypeAndParams(String local, String p) {
    if (needsSetting) {
      localType = local;
      params = p;
      needsSetting = false;
    }
  }
}





Types.LONGVARCHAR

 
/*
 Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 Use of this software is authorized pursuant to the terms of the license found at
 http://developer.java.sun.ru/berkeley_license.html.
 Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.  
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met: 
 - Redistribution of source code must retain the above copyright notice, 
 this list of conditions and the following disclaimer.
 - Redistribution in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 be used to endorse or promote products derived from this software without
 specific prior written permission.
 This software is provided "AS IS," without a warranty of any kind.  
 ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN")
 AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN
 IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 You acknowledge that this software is not designed, licensed or intended for
 use in the design, construction, operation or maintenance of any nuclear
 facility.

 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
 * Use of this software is authorized pursuant to the terms of the license found at
 * http://developer.java.sun.ru/berkeley_license.html.
 */
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;
    Statement stmt;
    try {
      Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
      System.err.print("ClassNotFoundException: ");
      System.err.println(e.getMessage());
    }
    try {
      con = DriverManager.getConnection(url, "myLogin", "myPassword");
      stmt = con.createStatement();
      Vector dataTypes = getDataTypes(con);
      String tableName;
      String columnName;
      String sqlType;
      String prompt = "Enter the new table name and hit Return: ";
      tableName = getInput(prompt);
      String createTableString = "create table " + tableName + " (";
      String commaAndSpace = ", ";
      boolean firstTime = true;
      while (true) {
        System.out.println("");
        prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
        columnName = getInput(prompt);
        if (firstTime) {
          if (columnName.length() == 0) {
            System.out.print("Need at least one column;");
            System.out.println(" please try again");
            continue;
          } else {
            createTableString += columnName + " ";
            firstTime = false;
          }
        } else if (columnName.length() == 0) {
          break;
        } else {
          createTableString += commaAndSpace + columnName + " ";
        }
        String localTypeName = null;
        String paramString = "";
        while (true) {
          System.out.println("");
          System.out.println("LIST OF TYPES YOU MAY USE:  ");
          boolean firstPrinted = true;
          int length = 0;
          for (int i = 0; i < dataTypes.size(); i++) {
            DataType dataType = (DataType) dataTypes.get(i);
            if (!dataType.needsToBeSet()) {
              if (!firstPrinted)
                System.out.print(commaAndSpace);
              else
                firstPrinted = false;
              System.out.print(dataType.getSQLType());
              length += dataType.getSQLType().length();
              if (length > 50) {
                System.out.println("");
                length = 0;
                firstPrinted = true;
              }
            }
          }
          System.out.println("");
          int index;
          prompt = "Enter a column type " + "from the list and hit Return:  ";
          sqlType = getInput(prompt);
          for (index = 0; index < dataTypes.size(); index++) {
            DataType dataType = (DataType) dataTypes.get(index);
            if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
              break;
            }
          }
          localTypeName = null;
          paramString = "";
          if (index < dataTypes.size()) { // there was a match
            String params;
            DataType dataType = (DataType) dataTypes.get(index);
            params = dataType.getParams();
            localTypeName = dataType.getLocalType();
            if (params != null) {
              prompt = "Enter " + params + ":  ";
              paramString = "(" + getInput(prompt) + ")";
            }
            break;
          } else { // use the name as given
            prompt = "Are you sure?  " + "Enter "y" or "n" and hit Return:  ";
            String check = getInput(prompt) + " ";
            check = check.toLowerCase().substring(0, 1);
            if (check.equals("n"))
              continue;
            else {
              localTypeName = sqlType;
              break;
            }
          }
        }
        createTableString += localTypeName + paramString;
      }
      createTableString += ")";
      System.out.println("");
      System.out.print("Your CREATE TABLE statement as ");
      System.out.println("sent to your DBMS:  ");
      System.out.println(createTableString);
      System.out.println("");
      stmt.executeUpdate(createTableString);
      stmt.close();
      con.close();
    } catch (SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
  }
  private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;
    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)
    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));
    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
      int codeNumber = rs.getInt("DATA_TYPE");
      String dbmsName = rs.getString("TYPE_NAME");
      String createParams = rs.getString("CREATE_PARAMS");
      if (codeNumber == Types.STRUCT && structName == null)
        structName = dbmsName;
      else if (codeNumber == Types.DISTINCT && distinctName == null)
        distinctName = dbmsName;
      else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
        javaName = dbmsName;
      else {
        for (int i = 0; i < dataTypes.size(); i++) {
          // find entry that matches the SQL code,
          // and if local type and params are not already set,
          // set them
          DataType type = (DataType) dataTypes.get(i);
          if (type.getCode() == codeNumber) {
            type.setLocalTypeAndParams(dbmsName, createParams);
          }
        }
      }
    }
    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
      String typeName = null;
      DataType dataType = null;
      if (dbmd.isCatalogAtStart())
        typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
            + rs.getString(3);
      else
        typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
            + rs.getString(1);
      switch (rs.getInt(5)) {
      case Types.STRUCT:
        dataType = new DataType(Types.STRUCT, typeName);
        dataType.setLocalTypeAndParams(structName, null);
        break;
      case Types.DISTINCT:
        dataType = new DataType(Types.DISTINCT, typeName);
        dataType.setLocalTypeAndParams(distinctName, null);
        break;
      case Types.JAVA_OBJECT:
        dataType = new DataType(Types.JAVA_OBJECT, typeName);
        dataType.setLocalTypeAndParams(javaName, null);
        break;
      }
      dataTypes.add(dataType);
    }
    return dataTypes;
  }
  private static String getInput(String prompt) throws SQLException {
    System.out.print(prompt);
    System.out.flush();
    try {
      java.io.BufferedReader bin;
      bin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
      String result = bin.readLine();
      return result;
    } catch (java.io.IOException ex) {
      System.out.println("Caught java.io.IOException:");
      System.out.println(ex.getMessage());
      return "";
    }
  }
}
class DataType {
  private int code;
  private String SQLType;
  private String localType = null;
  private String params = null;
  private boolean needsSetting = true;
  public DataType(int code, String SQLType) {
    this.code = code;
    this.SQLType = SQLType;
  }
  public boolean needsToBeSet() {
    return needsSetting;
  }
  public int getCode() {
    return code;
  }
  public String getSQLType() {
    return SQLType;
  }
  public String getLocalType() {
    return localType;
  }
  public String getParams() {
    return params;
  }
  public void setLocalTypeAndParams(String local, String p) {
    if (needsSetting) {
      localType = local;
      params = p;
      needsSetting = false;
    }
  }
}





Types.NULL

 
/*
 Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 Use of this software is authorized pursuant to the terms of the license found at
 http://developer.java.sun.ru/berkeley_license.html.
 Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.  
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met: 
 - Redistribution of source code must retain the above copyright notice, 
 this list of conditions and the following disclaimer.
 - Redistribution in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 be used to endorse or promote products derived from this software without
 specific prior written permission.
 This software is provided "AS IS," without a warranty of any kind.  
 ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN")
 AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN
 IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 You acknowledge that this software is not designed, licensed or intended for
 use in the design, construction, operation or maintenance of any nuclear
 facility.

 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
 * Use of this software is authorized pursuant to the terms of the license found at
 * http://developer.java.sun.ru/berkeley_license.html.
 */
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;
    Statement stmt;
    try {
      Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
      System.err.print("ClassNotFoundException: ");
      System.err.println(e.getMessage());
    }
    try {
      con = DriverManager.getConnection(url, "myLogin", "myPassword");
      stmt = con.createStatement();
      Vector dataTypes = getDataTypes(con);
      String tableName;
      String columnName;
      String sqlType;
      String prompt = "Enter the new table name and hit Return: ";
      tableName = getInput(prompt);
      String createTableString = "create table " + tableName + " (";
      String commaAndSpace = ", ";
      boolean firstTime = true;
      while (true) {
        System.out.println("");
        prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
        columnName = getInput(prompt);
        if (firstTime) {
          if (columnName.length() == 0) {
            System.out.print("Need at least one column;");
            System.out.println(" please try again");
            continue;
          } else {
            createTableString += columnName + " ";
            firstTime = false;
          }
        } else if (columnName.length() == 0) {
          break;
        } else {
          createTableString += commaAndSpace + columnName + " ";
        }
        String localTypeName = null;
        String paramString = "";
        while (true) {
          System.out.println("");
          System.out.println("LIST OF TYPES YOU MAY USE:  ");
          boolean firstPrinted = true;
          int length = 0;
          for (int i = 0; i < dataTypes.size(); i++) {
            DataType dataType = (DataType) dataTypes.get(i);
            if (!dataType.needsToBeSet()) {
              if (!firstPrinted)
                System.out.print(commaAndSpace);
              else
                firstPrinted = false;
              System.out.print(dataType.getSQLType());
              length += dataType.getSQLType().length();
              if (length > 50) {
                System.out.println("");
                length = 0;
                firstPrinted = true;
              }
            }
          }
          System.out.println("");
          int index;
          prompt = "Enter a column type " + "from the list and hit Return:  ";
          sqlType = getInput(prompt);
          for (index = 0; index < dataTypes.size(); index++) {
            DataType dataType = (DataType) dataTypes.get(index);
            if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
              break;
            }
          }
          localTypeName = null;
          paramString = "";
          if (index < dataTypes.size()) { // there was a match
            String params;
            DataType dataType = (DataType) dataTypes.get(index);
            params = dataType.getParams();
            localTypeName = dataType.getLocalType();
            if (params != null) {
              prompt = "Enter " + params + ":  ";
              paramString = "(" + getInput(prompt) + ")";
            }
            break;
          } else { // use the name as given
            prompt = "Are you sure?  " + "Enter "y" or "n" and hit Return:  ";
            String check = getInput(prompt) + " ";
            check = check.toLowerCase().substring(0, 1);
            if (check.equals("n"))
              continue;
            else {
              localTypeName = sqlType;
              break;
            }
          }
        }
        createTableString += localTypeName + paramString;
      }
      createTableString += ")";
      System.out.println("");
      System.out.print("Your CREATE TABLE statement as ");
      System.out.println("sent to your DBMS:  ");
      System.out.println(createTableString);
      System.out.println("");
      stmt.executeUpdate(createTableString);
      stmt.close();
      con.close();
    } catch (SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
  }
  private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;
    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)
    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));
    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
      int codeNumber = rs.getInt("DATA_TYPE");
      String dbmsName = rs.getString("TYPE_NAME");
      String createParams = rs.getString("CREATE_PARAMS");
      if (codeNumber == Types.STRUCT && structName == null)
        structName = dbmsName;
      else if (codeNumber == Types.DISTINCT && distinctName == null)
        distinctName = dbmsName;
      else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
        javaName = dbmsName;
      else {
        for (int i = 0; i < dataTypes.size(); i++) {
          // find entry that matches the SQL code,
          // and if local type and params are not already set,
          // set them
          DataType type = (DataType) dataTypes.get(i);
          if (type.getCode() == codeNumber) {
            type.setLocalTypeAndParams(dbmsName, createParams);
          }
        }
      }
    }
    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
      String typeName = null;
      DataType dataType = null;
      if (dbmd.isCatalogAtStart())
        typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
            + rs.getString(3);
      else
        typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
            + rs.getString(1);
      switch (rs.getInt(5)) {
      case Types.STRUCT:
        dataType = new DataType(Types.STRUCT, typeName);
        dataType.setLocalTypeAndParams(structName, null);
        break;
      case Types.DISTINCT:
        dataType = new DataType(Types.DISTINCT, typeName);
        dataType.setLocalTypeAndParams(distinctName, null);
        break;
      case Types.JAVA_OBJECT:
        dataType = new DataType(Types.JAVA_OBJECT, typeName);
        dataType.setLocalTypeAndParams(javaName, null);
        break;
      }
      dataTypes.add(dataType);
    }
    return dataTypes;
  }
  private static String getInput(String prompt) throws SQLException {
    System.out.print(prompt);
    System.out.flush();
    try {
      java.io.BufferedReader bin;
      bin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
      String result = bin.readLine();
      return result;
    } catch (java.io.IOException ex) {
      System.out.println("Caught java.io.IOException:");
      System.out.println(ex.getMessage());
      return "";
    }
  }
}
class DataType {
  private int code;
  private String SQLType;
  private String localType = null;
  private String params = null;
  private boolean needsSetting = true;
  public DataType(int code, String SQLType) {
    this.code = code;
    this.SQLType = SQLType;
  }
  public boolean needsToBeSet() {
    return needsSetting;
  }
  public int getCode() {
    return code;
  }
  public String getSQLType() {
    return SQLType;
  }
  public String getLocalType() {
    return localType;
  }
  public String getParams() {
    return params;
  }
  public void setLocalTypeAndParams(String local, String p) {
    if (needsSetting) {
      localType = local;
      params = p;
      needsSetting = false;
    }
  }
}





Types.TIMESTAMP

 
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
  public static void main(String[] args) throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    Class.forName(driver).newInstance();
    String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    Connection conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
    printColumnInfo(rs);
    printColumnNames(rs);
    processRs(rs);
    rs = stmt.executeQuery("SELECT * FROM Location");
    printColumnInfo(rs);
    printColumnNames(rs);
    processRs(rs);
    conn.close();
  }
  public static void processRs(ResultSet rs) throws SQLException {
    ResultSetMetaData rmd = rs.getMetaData();
    while (rs.next()) {
      for (int col = 1; col <= rmd.getColumnCount(); col++)
        getData(rs, rmd.getColumnType(col), col);
    }
  }
  public static void printColumnNames(ResultSet rs) throws SQLException {
    ResultSetMetaData rmd = rs.getMetaData();
    for (int col = 1; col <= rmd.getColumnCount(); col++)
      System.out.println(rmd.getColumnName(col) + " ");
  }
  public static void getData(ResultSet rs, int type, int colIdx) throws SQLException {
    switch (type) {
    case java.sql.Types.CHAR:
    case java.sql.Types.VARCHAR:
      System.out.println(rs.getString(colIdx));
      break;
    case java.sql.Types.INTEGER:
      int i = rs.getInt(colIdx);
      System.out.println(i);
      break;
    case java.sql.Types.NUMERIC:
      BigDecimal bd = rs.getBigDecimal(colIdx);
      System.out.println(bd.toString());
      break;
    case java.sql.Types.TIMESTAMP:
    case java.sql.Types.DATE:
      java.sql.Date d = rs.getDate(colIdx);
      System.out.println(d.toString());
      break;
    }
  }
  public static void printColumnInfo(ResultSet rs) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();
    for (int colIdx = 1; colIdx <= cols; colIdx++) {
      String name = rsmd.getColumnName(colIdx);
      int type = rsmd.getColumnType(colIdx);
      String typeName = rsmd.getColumnTypeName(colIdx);
      System.out.println(name + ", " + type + ", " + typeName);
    }
  }
}





Types.VARBINARY

 
/*
 Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 Use of this software is authorized pursuant to the terms of the license found at
 http://developer.java.sun.ru/berkeley_license.html.
 Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.  
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met: 
 - Redistribution of source code must retain the above copyright notice, 
 this list of conditions and the following disclaimer.
 - Redistribution in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 be used to endorse or promote products derived from this software without
 specific prior written permission.
 This software is provided "AS IS," without a warranty of any kind.  
 ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN")
 AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
 LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN
 IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 You acknowledge that this software is not designed, licensed or intended for
 use in the design, construction, operation or maintenance of any nuclear
 facility.

 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
 * Use of this software is authorized pursuant to the terms of the license found at
 * http://developer.java.sun.ru/berkeley_license.html.
 */
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;
    Statement stmt;
    try {
      Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
      System.err.print("ClassNotFoundException: ");
      System.err.println(e.getMessage());
    }
    try {
      con = DriverManager.getConnection(url, "myLogin", "myPassword");
      stmt = con.createStatement();
      Vector dataTypes = getDataTypes(con);
      String tableName;
      String columnName;
      String sqlType;
      String prompt = "Enter the new table name and hit Return: ";
      tableName = getInput(prompt);
      String createTableString = "create table " + tableName + " (";
      String commaAndSpace = ", ";
      boolean firstTime = true;
      while (true) {
        System.out.println("");
        prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
        columnName = getInput(prompt);
        if (firstTime) {
          if (columnName.length() == 0) {
            System.out.print("Need at least one column;");
            System.out.println(" please try again");
            continue;
          } else {
            createTableString += columnName + " ";
            firstTime = false;
          }
        } else if (columnName.length() == 0) {
          break;
        } else {
          createTableString += commaAndSpace + columnName + " ";
        }
        String localTypeName = null;
        String paramString = "";
        while (true) {
          System.out.println("");
          System.out.println("LIST OF TYPES YOU MAY USE:  ");
          boolean firstPrinted = true;
          int length = 0;
          for (int i = 0; i < dataTypes.size(); i++) {
            DataType dataType = (DataType) dataTypes.get(i);
            if (!dataType.needsToBeSet()) {
              if (!firstPrinted)
                System.out.print(commaAndSpace);
              else
                firstPrinted = false;
              System.out.print(dataType.getSQLType());
              length += dataType.getSQLType().length();
              if (length > 50) {
                System.out.println("");
                length = 0;
                firstPrinted = true;
              }
            }
          }
          System.out.println("");
          int index;
          prompt = "Enter a column type " + "from the list and hit Return:  ";
          sqlType = getInput(prompt);
          for (index = 0; index < dataTypes.size(); index++) {
            DataType dataType = (DataType) dataTypes.get(index);
            if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
              break;
            }
          }
          localTypeName = null;
          paramString = "";
          if (index < dataTypes.size()) { // there was a match
            String params;
            DataType dataType = (DataType) dataTypes.get(index);
            params = dataType.getParams();
            localTypeName = dataType.getLocalType();
            if (params != null) {
              prompt = "Enter " + params + ":  ";
              paramString = "(" + getInput(prompt) + ")";
            }
            break;
          } else { // use the name as given
            prompt = "Are you sure?  " + "Enter "y" or "n" and hit Return:  ";
            String check = getInput(prompt) + " ";
            check = check.toLowerCase().substring(0, 1);
            if (check.equals("n"))
              continue;
            else {
              localTypeName = sqlType;
              break;
            }
          }
        }
        createTableString += localTypeName + paramString;
      }
      createTableString += ")";
      System.out.println("");
      System.out.print("Your CREATE TABLE statement as ");
      System.out.println("sent to your DBMS:  ");
      System.out.println(createTableString);
      System.out.println("");
      stmt.executeUpdate(createTableString);
      stmt.close();
      con.close();
    } catch (SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
  }
  private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;
    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)
    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));
    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
      int codeNumber = rs.getInt("DATA_TYPE");
      String dbmsName = rs.getString("TYPE_NAME");
      String createParams = rs.getString("CREATE_PARAMS");
      if (codeNumber == Types.STRUCT && structName == null)
        structName = dbmsName;
      else if (codeNumber == Types.DISTINCT && distinctName == null)
        distinctName = dbmsName;
      else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
        javaName = dbmsName;
      else {
        for (int i = 0; i < dataTypes.size(); i++) {
          // find entry that matches the SQL code,
          // and if local type and params are not already set,
          // set them
          DataType type = (DataType) dataTypes.get(i);
          if (type.getCode() == codeNumber) {
            type.setLocalTypeAndParams(dbmsName, createParams);
          }
        }
      }
    }
    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
      String typeName = null;
      DataType dataType = null;
      if (dbmd.isCatalogAtStart())
        typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
            + rs.getString(3);
      else
        typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
            + rs.getString(1);
      switch (rs.getInt(5)) {
      case Types.STRUCT:
        dataType = new DataType(Types.STRUCT, typeName);
        dataType.setLocalTypeAndParams(structName, null);
        break;
      case Types.DISTINCT:
        dataType = new DataType(Types.DISTINCT, typeName);
        dataType.setLocalTypeAndParams(distinctName, null);
        break;
      case Types.JAVA_OBJECT:
        dataType = new DataType(Types.JAVA_OBJECT, typeName);
        dataType.setLocalTypeAndParams(javaName, null);
        break;
      }
      dataTypes.add(dataType);
    }
    return dataTypes;
  }
  private static String getInput(String prompt) throws SQLException {
    System.out.print(prompt);
    System.out.flush();
    try {
      java.io.BufferedReader bin;
      bin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
      String result = bin.readLine();
      return result;
    } catch (java.io.IOException ex) {
      System.out.println("Caught java.io.IOException:");
      System.out.println(ex.getMessage());
      return "";
    }
  }
}
class DataType {
  private int code;
  private String SQLType;
  private String localType = null;
  private String params = null;
  private boolean needsSetting = true;
  public DataType(int code, String SQLType) {
    this.code = code;
    this.SQLType = SQLType;
  }
  public boolean needsToBeSet() {
    return needsSetting;
  }
  public int getCode() {
    return code;
  }
  public String getSQLType() {
    return SQLType;
  }
  public String getLocalType() {
    return localType;
  }
  public String getParams() {
    return params;
  }
  public void setLocalTypeAndParams(String local, String p) {
    if (needsSetting) {
      localType = local;
      params = p;
      needsSetting = false;
    }
  }
}





Types.VARCHAR

 
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
  public static void main(String[] args) throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    Class.forName(driver).newInstance();
    String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    Connection conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
    printColumnInfo(rs);
    printColumnNames(rs);
    processRs(rs);
    rs = stmt.executeQuery("SELECT * FROM Location");
    printColumnInfo(rs);
    printColumnNames(rs);
    processRs(rs);
    conn.close();
  }
  public static void processRs(ResultSet rs) throws SQLException {
    ResultSetMetaData rmd = rs.getMetaData();
    while (rs.next()) {
      for (int col = 1; col <= rmd.getColumnCount(); col++)
        getData(rs, rmd.getColumnType(col), col);
    }
  }
  public static void printColumnNames(ResultSet rs) throws SQLException {
    ResultSetMetaData rmd = rs.getMetaData();
    for (int col = 1; col <= rmd.getColumnCount(); col++)
      System.out.println(rmd.getColumnName(col) + " ");
  }
  public static void getData(ResultSet rs, int type, int colIdx) throws SQLException {
    switch (type) {
    case java.sql.Types.CHAR:
    case java.sql.Types.VARCHAR:
      System.out.println(rs.getString(colIdx));
      break;
    case java.sql.Types.INTEGER:
      int i = rs.getInt(colIdx);
      System.out.println(i);
      break;
    case java.sql.Types.NUMERIC:
      BigDecimal bd = rs.getBigDecimal(colIdx);
      System.out.println(bd.toString());
      break;
    case java.sql.Types.TIMESTAMP:
    case java.sql.Types.DATE:
      java.sql.Date d = rs.getDate(colIdx);
      System.out.println(d.toString());
      break;
    }
  }
  public static void printColumnInfo(ResultSet rs) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();
    for (int colIdx = 1; colIdx <= cols; colIdx++) {
      String name = rsmd.getColumnName(colIdx);
      int type = rsmd.getColumnType(colIdx);
      String typeName = rsmd.getColumnTypeName(colIdx);
      System.out.println(name + ", " + type + ", " + typeName);
    }
  }
}