Example usage for java.sql Statement close

List of usage examples for java.sql Statement close

Introduction

In this page you can find the example usage for java.sql Statement close.

Prototype

void close() throws SQLException;

Source Link

Document

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

Usage

From source file:com.quest.orahive.HiveJdbcClient.java

public static void main(String[] args) {

    long mainStartTime = System.nanoTime();

    Configuration conf = new Configuration();
    Options options = new Options();

    parseGeneralOptions(options, conf, args); //<- log4j will now be configured.

    showWelcomeMessage();/* w  w w. ja  va2  s.  c  o  m*/

    if (args.length == 0 || userWantsToSeeHelp(args)) {
        printCommandLineHelp(options);
        System.exit(0);
    }

    checkConfiguration(conf);

    OraHiveOptions opts = getOraHiveOptions(conf);
    OraHiveCounters counters = new OraHiveCounters();

    try {
        Connection hiveConnection = createHiveJdbcConnection(opts.hiveJdbcUrl, opts.hiveUserName,
                opts.hivePassword);
        try {
            Connection oracleConnection = createOracleJdbcConnection(opts.oracleJdbcUrl, opts.oracleUserName,
                    opts.oraclePassword);
            try {
                initializeOracleSession(oracleConnection, opts);

                Statement statement = hiveConnection.createStatement();

                LOG.info("Running: " + opts.hql);

                // Execute Hive Query...
                long start = System.nanoTime();
                ResultSet hiveResultSet = statement.executeQuery(opts.hql);
                counters.hiveQueryTimeNanoSec = System.nanoTime() - start;

                // Get column definitions from the Hive resultset...
                List<OracleTableColumn> oracleColumns = getOracleTableColumnsForHiveResults(hiveResultSet);

                if (opts.exportMode.equals(Constants.ExportMode.CREATE)) {
                    // Create an Oracle table based on the columns in the Hive resultset...
                    createOracleTableWithRetry(opts, oracleColumns, oracleConnection); //<- Lets the user retry this if it fails.
                }

                // Generate the Oracle insert statement...
                String insertSql = generateOracleInsertStatement(opts, oracleColumns);

                // Insert the Hive data into Oracle...
                insertHiveResultsIntoOracleTable(opts, insertSql, oracleColumns, oracleConnection,
                        hiveResultSet, counters);

                //hiveResultSet.close();   //<- Not required/supported
                statement.close();
            } finally {
                oracleConnection.close();
            }
        } finally {
            hiveConnection.close();
        }

    } catch (SQLException ex) {
        LOG.error(String.format("An error occurred in %s.", Constants.ORAHIVE_PRODUCT_NAME), ex);
    }

    LOG.info(String.format("\n\n********************************************************************\n"
            + "\tTotal time                        : %s sec.\n" + "\tNumber of records processed       : %s\n"
            + "\tTime spent executing HQL statement: %s sec.\n"
            + "\tTime spent fetching Hive data     : %s sec.\n"
            + "\tTime spent inserting into Oracle  : %s sec.",
            (System.nanoTime() - mainStartTime) / Math.pow(10, 9), counters.rowsProcessed,
            counters.hiveQueryTimeNanoSec / Math.pow(10, 9), counters.hiveFetchTimeNanoSec / Math.pow(10, 9),
            counters.oracleInsertTimeNanoSec / Math.pow(10, 9)));

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    DatabaseMetaData dbMetaData = conn.getMetaData();
    ResultSet rs = dbMetaData.getProcedureColumns(conn.getCatalog(), null, "procedureNamePattern",
            "columnNamePattern");

    while (rs.next()) {
        // get stored procedure metadata
        String procedureCatalog = rs.getString(1);
        String procedureSchema = rs.getString(2);
        String procedureName = rs.getString(3);
        String columnName = rs.getString(4);
        short columnReturn = rs.getShort(5);
        int columnDataType = rs.getInt(6);
        String columnReturnTypeName = rs.getString(7);
        int columnPrecision = rs.getInt(8);
        int columnByteLength = rs.getInt(9);
        short columnScale = rs.getShort(10);
        short columnRadix = rs.getShort(11);
        short columnNullable = rs.getShort(12);
        String columnRemarks = rs.getString(13);

        System.out.println("stored Procedure name=" + procedureName);
        System.out.println("procedureCatalog=" + procedureCatalog);
        System.out.println("procedureSchema=" + procedureSchema);
        System.out.println("procedureName=" + procedureName);
        System.out.println("columnName=" + columnName);
        System.out.println("columnReturn=" + columnReturn);
        System.out.println("columnDataType=" + columnDataType);
        System.out.println("columnReturnTypeName=" + columnReturnTypeName);
        System.out.println("columnPrecision=" + columnPrecision);
        System.out.println("columnByteLength=" + columnByteLength);
        System.out.println("columnScale=" + columnScale);
        System.out.println("columnRadix=" + columnRadix);
        System.out.println("columnNullable=" + columnNullable);
        System.out.println("columnRemarks=" + columnRemarks);
    }//from w  w  w  .  ja  v a  2s  . co  m

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet indexInformation = null;
    DatabaseMetaData meta = conn.getMetaData();

    // The '_' character represents any single character.
    // The '%' character represents any sequence of zero
    // or more characters.
    indexInformation = meta.getIndexInfo(conn.getCatalog(), null, "survey", true, true);
    while (indexInformation.next()) {
        String dbCatalog = indexInformation.getString("TABLE_CATALOG");
        String dbSchema = indexInformation.getString("TABLE_SCHEMA");
        String dbTableName = indexInformation.getString("TABLE_NAME");
        boolean dbNoneUnique = indexInformation.getBoolean("NON_UNIQUE");
        String dbIndexQualifier = indexInformation.getString("INDEX_QUALIFIER");
        String dbIndexName = indexInformation.getString("INDEX_NAME");
        short dbType = indexInformation.getShort("TYPE");
        short dbOrdinalPosition = indexInformation.getShort("ORDINAL_POSITION");
        String dbColumnName = indexInformation.getString("COLUMN_NAME");
        String dbAscOrDesc = indexInformation.getString("ASC_OR_DESC");
        int dbCardinality = indexInformation.getInt("CARDINALITY");
        int dbPages = indexInformation.getInt("PAGES");
        String dbFilterCondition = indexInformation.getString("FILTER_CONDITION");

        System.out.println("index name=" + dbIndexName);
        System.out.println("table=" + dbTableName);
        System.out.println("column=" + dbColumnName);
        System.out.println("catalog=" + dbCatalog);
        System.out.println("schema=" + dbSchema);
        System.out.println("nonUnique=" + dbNoneUnique);
        System.out.println("indexQualifier=" + dbIndexQualifier);
        System.out.println("type=" + dbType);
        System.out.println("ordinalPosition=" + dbOrdinalPosition);
        System.out.println("ascendingOrDescending=" + dbAscOrDesc);
        System.out.println("cardinality=" + dbCardinality);
        System.out.println("pages=" + dbPages);
        System.out.println("filterCondition=" + dbFilterCondition);
    }/*  w  w w .  ja  v a  2 s .com*/

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar, age int);");
    st.executeUpdate("insert into survey (id,name,age ) values (1,'nameValue', 10)");
    st.executeUpdate("insert into survey (id,name,age ) values (2,'anotherValue', 100)");

    FilteredRowSet frs = new FilteredRowSetImpl();
    frs.setUsername("sa");
    frs.setPassword("");
    frs.setUrl("jdbc:hsqldb:data/tutorial");
    frs.setCommand("SELECT id, name, age FROM survey");
    frs.execute();/*ww w  .j  ava 2s.co m*/

    System.out.println("--- Unfiltered RowSet: ---");
    while (frs.next()) {
        System.out.println(frs.getRow() + " - " + frs.getString("id") + ":" + frs.getString("name") + ":"
                + frs.getInt("age"));
    }
    // create a filter that restricts entries in
    // the age column to be between 7 and 10
    AgeFilter filter = new AgeFilter(7, 10, 3);

    // set the filter.
    frs.beforeFirst();
    frs.setFilter(filter);

    // go to the beginning of the Rowset
    System.out.println("--- Filtered RowSet: ---");

    // show filtered data
    while (frs.next()) {
        System.out.println(frs.getRow() + " - " + frs.getString("id") + ":" + frs.getString("name") + ":"
                + frs.getInt("age"));
    }

    System.out.println("--- Try to insert new records ---");

    // Try to add an employee with age = 90 (allowed by filter)
    frs.moveToInsertRow();
    frs.updateString(1, "999");
    frs.updateString(2, "Andre");
    frs.updateInt(3, 90);
    frs.insertRow();
    frs.moveToCurrentRow();
    frs.acceptChanges();

    // try to add an survey with age = 65 (not allowed by filter)
    frs.moveToInsertRow();
    frs.updateString(1, "123");
    frs.updateString(2, "Jeff");
    frs.updateInt(3, 65);
    frs.insertRow();
    frs.moveToCurrentRow();
    frs.acceptChanges();

    // scroll to first row of rowset
    frs.beforeFirst();
    // display rows in FilteredRowset
    System.out.println("FilteredRowSet after trying to insert Jeff (age 65) and Andre (age 90):");
    while (frs.next()) {
        System.out.println(frs.getRow() + " - " + frs.getString("id") + ":" + frs.getString("name") + ":"
                + frs.getInt("age"));
    }

    frs.close();
    st.close();
    frs.close();
}

From source file:SimpleProgramToAccessOracleDatabase.java

public static void main(String[] args) throws SQLException {
    Connection conn = null; // connection object
    Statement stmt = null; // statement object
    ResultSet rs = null; // result set object
    try {/*  w w w.j  a v a 2 s  .  com*/
        conn = getConnection(); // without Connection, can not do much
        // create a statement: This object will be used for executing
        // a static SQL statement and returning the results it produces.
        stmt = conn.createStatement();
        // start a transaction
        conn.setAutoCommit(false);

        // create a table called cats_tricks
        stmt.executeUpdate("CREATE TABLE cats_tricks " + "(name VARCHAR2(30), trick VARCHAR2(30))");
        // insert two new records to the cats_tricks table
        stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'r')");
        stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'j')");

        // commit the transaction
        conn.commit();

        // set auto commit to true (from now on every single
        // statement will be treated as a single transaction
        conn.setAutoCommit(true);

        // get all of the the records from the cats_tricks table
        rs = stmt.executeQuery("SELECT name, trick FROM cats_tricks");

        // iterate the result set and get one row at a time
        while (rs.next()) {
            String name = rs.getString(1); // 1st column in query
            String trick = rs.getString(2); // 2nd column in query
            System.out.println("name=" + name);
            System.out.println("trick=" + trick);
            System.out.println("==========");
        }
    } catch (ClassNotFoundException ce) {
        // if the driver class not found, then we will be here
        System.out.println(ce.getMessage());
    } catch (SQLException e) {
        // something went wrong, we are handling the exception here
        if (conn != null) {
            conn.rollback();
            conn.setAutoCommit(true);
        }

        System.out.println("--- SQLException caught ---");
        // iterate and get all of the errors as much as possible.
        while (e != null) {
            System.out.println("Message   : " + e.getMessage());
            System.out.println("SQLState  : " + e.getSQLState());
            System.out.println("ErrorCode : " + e.getErrorCode());
            System.out.println("---");
            e = e.getNextException();
        }
    } finally { // close db resources
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
        }

    }
}

From source file:fr.eo.util.dumper.Dumper.java

/**
 * @param args//from  w  w  w .  ja v  a2 s.c om
 */
public static void main(String[] args) {

    String appName = args[0];

    System.out.println("Starting dumper ...");

    Statement stmt = null;

    try {
        System.out.println("Getting database connection ...");
        Connection conn = getJtdsConnection();

        List<RequestDefinitionBean> requests = RequestDefinitionParser.getRequests(appName);

        assetFolder = RequestDefinitionParser.getAppBaseDir(appName) + "assets/";

        for (RequestDefinitionBean request : requests) {
            int currentFileSize = 0, cpt = 1;
            stmt = conn.createStatement();
            System.out.println("Dumping " + request.name + "...");
            ResultSet rs = stmt.executeQuery(request.sql);
            BufferedWriter bw = getWriter(request.name, cpt);
            bw.append(COPYRIGHTS);
            currentFileSize += COPYRIGHTS.length();
            bw.append("--" + request.name + "\n");
            while (rs.next()) {
                StringBuilder sb = new StringBuilder();
                sb.append("INSERT INTO ");
                sb.append(request.table).append(" VALUES (");
                int pos = 0;
                for (String fieldName : request.fields) {
                    String str = getFieldValue(request, pos, rs, fieldName);
                    sb.append(str);
                    pos++;
                    if (pos < request.fields.size()) {
                        sb.append(",");
                    }
                }
                sb.append(");\n");
                currentFileSize += sb.length();
                bw.append(sb.toString());
                bw.flush();

                if (currentFileSize > MAX_FILE_SIZE) {
                    bw.close();

                    bw = getWriter(request.name, ++cpt);
                    bw.append(COPYRIGHTS);
                    bw.append("--" + request.name + "\n");
                    currentFileSize = COPYRIGHTS.length();
                }
            }
            bw.flush();
            bw.close();
        }

        System.out.println("done.");

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    DumpFilesDescriptor descriptor = new DumpFilesDescriptor();
    descriptor.lineNumbers = getDumpLinesNumber();
    descriptor.dumpFileNames = dumpFileNames;
    writeDescriptorFile(descriptor);

    System.out.println("nb :" + descriptor.lineNumbers);
}

From source file:movierecommend.MovieRecommend.java

public static void main(String[] args) throws ClassNotFoundException, SQLException {
    String url = "jdbc:sqlserver://localhost;databaseName=MovieDB;integratedSecurity=true";
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection conn = DriverManager.getConnection(url);

    Statement stm = conn.createStatement();
    ResultSet rsRecnik = stm.executeQuery("SELECT Recnik FROM Recnik WHERE (ID_Zanra = 1)"); //citam recnik iz baze za odredjeni zanr
    String recnik[] = null;/* w  w w .  ja v a  2 s  .c  o  m*/

    while (rsRecnik.next()) {
        recnik = rsRecnik.getString("Recnik").split(","); //delim recnik na reci

    }

    ResultSet rsFilmovi = stm.executeQuery(
            "SELECT TOP (200) Naziv_Filma, LemmaPlots, " + "ID_Filma FROM Film WHERE (ID_Zanra = 1)");
    List<Film> listaFilmova = new ArrayList<>();
    Film f = null;
    int rb = 0;
    while (rsFilmovi.next()) {
        f = new Film(rb, Integer.parseInt(rsFilmovi.getString("ID_Filma")), rsFilmovi.getString("Naziv_Filma"),
                rsFilmovi.getString("LemmaPlots"));
        listaFilmova.add(f);
        rb++;

    }
    //kreiranje vektorskog modela
    M = MatrixUtils.createRealMatrix(recnik.length, listaFilmova.size());
    System.out.println("Prva tezinska matrica");

    for (int i = 0; i < recnik.length; i++) {
        String recBaza = recnik[i];
        for (Film film : listaFilmova) {
            for (String lemmaRec : film.getPlotLema()) {
                if (recBaza.equals(lemmaRec)) {
                    M.setEntry(i, film.getRb(), M.getEntry(i, film.getRb()) + 1);
                }
            }
        }
    }
    //racunanje tf-idf
    System.out.println("td-idf");
    M = LSA.calculateTfIdf(M);
    System.out.println("SVD");
    //SVD
    SingularValueDecomposition svd = new SingularValueDecomposition(M);
    RealMatrix V = svd.getV();
    RealMatrix Vk = V.getSubMatrix(0, V.getRowDimension() - 1, 0, brojDimenzija - 1); //dimenzija je poslednji argument
    //kosinusna slicnost
    System.out.println("Cosin simmilarity");
    CallableStatement stmTop = conn.prepareCall("{call Dodaj_TopList(?,?,?)}");

    for (int j = 0; j < listaFilmova.size(); j++) {
        Film fl = listaFilmova.get(j);
        List<Film> lFilmova1 = new ArrayList<>();
        lFilmova1.add(listaFilmova.get(j));
        double sim = 0.0;
        for (int k = 0; k < listaFilmova.size(); k++) {
            // System.out.println(listaFilmova.size());                
            sim = LSA.cosinSim(j, k, Vk.transpose());
            listaFilmova.get(k).setSimilarity(sim);
            lFilmova1.add(listaFilmova.get(k));
        }
        Collections.sort(lFilmova1);
        for (int k = 2; k < 13; k++) {
            stmTop.setString(1, fl.getID() + "");
            stmTop.setString(2, lFilmova1.get(k).getID() + "");
            stmTop.setString(3, lFilmova1.get(k).getSimilarity() + "");
            stmTop.execute();
        }

    }

    stm.close();
    rsRecnik.close();
    rsFilmovi.close();
    conn.close();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    st = conn.createStatement();/* w  w w  . j ava 2s . co  m*/
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    ResultSetMetaData rsMetaData = rs.getMetaData();

    int numberOfColumns = rsMetaData.getColumnCount();
    System.out.println("resultSet MetaData column Count=" + numberOfColumns);

    for (int i = 1; i <= numberOfColumns; i++) {
        System.out.println("column MetaData ");
        System.out.println("column number " + i);
        // indicates the designated column's normal maximum width in
        // characters
        System.out.println(rsMetaData.getColumnDisplaySize(i));
        // gets the designated column's suggested title
        // for use in printouts and displays.
        System.out.println(rsMetaData.getColumnLabel(i));
        // get the designated column's name.
        System.out.println(rsMetaData.getColumnName(i));

        // get the designated column's SQL type.
        System.out.println(rsMetaData.getColumnType(i));

        // get the designated column's SQL type name.
        System.out.println(rsMetaData.getColumnTypeName(i));

        // get the designated column's class name.
        System.out.println(rsMetaData.getColumnClassName(i));

        // get the designated column's table name.
        System.out.println(rsMetaData.getTableName(i));

        // get the designated column's number of decimal digits.
        System.out.println(rsMetaData.getPrecision(i));

        // gets the designated column's number of
        // digits to right of the decimal point.
        System.out.println(rsMetaData.getScale(i));

        // indicates whether the designated column is
        // automatically numbered, thus read-only.
        System.out.println(rsMetaData.isAutoIncrement(i));

        // indicates whether the designated column is a cash value.
        System.out.println(rsMetaData.isCurrency(i));

        // indicates whether a write on the designated
        // column will succeed.
        System.out.println(rsMetaData.isWritable(i));

        // indicates whether a write on the designated
        // column will definitely succeed.
        System.out.println(rsMetaData.isDefinitelyWritable(i));

        // indicates the nullability of values
        // in the designated column.
        System.out.println(rsMetaData.isNullable(i));

        // Indicates whether the designated column
        // is definitely not writable.
        System.out.println(rsMetaData.isReadOnly(i));

        // Indicates whether a column's case matters
        // in the designated column.
        System.out.println(rsMetaData.isCaseSensitive(i));

        // Indicates whether a column's case matters
        // in the designated column.
        System.out.println(rsMetaData.isSearchable(i));

        // indicates whether values in the designated
        // column are signed numbers.
        System.out.println(rsMetaData.isSigned(i));

        // Gets the designated column's table's catalog name.
        System.out.println(rsMetaData.getCatalogName(i));

        // Gets the designated column's table's schema name.
        System.out.println(rsMetaData.getSchemaName(i));
    }

    st.close();
    conn.close();
}

From source file:InsertStores.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*  w  ww .  j  ava 2  s  .  c o  m*/
    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();
        con.setAutoCommit(false);

        String insertStore1 = "INSERT INTO STORES VALUES (" + "100001, "
                + "ADDRESS(888, 'Main_Street', 'Rancho_Alegre', " + "'CA', '94049'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))";

        stmt.addBatch(insertStore1);

        String insertStore2 = "INSERT INTO STORES VALUES (" + "100002, "
                + "ADDRESS(1560, 'Alder', 'Ochos_Pinos', " + "'CA', '94049'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))";

        stmt.addBatch(insertStore2);

        String insertStore3 = "INSERT INTO STORES VALUES (" + "100003, "
                + "ADDRESS(4344, 'First_Street', 'Verona', " + "'CA', '94545'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))";

        stmt.addBatch(insertStore3);

        String insertStore4 = "INSERT INTO STORES VALUES (" + "100004, "
                + "ADDRESS(321, 'Sandy_Way', 'La_Playa', " + "'CA', '94544'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))";

        stmt.addBatch(insertStore4);

        String insertStore5 = "INSERT INTO STORES VALUES (" + "100005, "
                + "ADDRESS(1000, 'Clover_Road', 'Happyville', " + "'CA', '90566'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000003))";

        stmt.addBatch(insertStore5);

        int[] updateCounts = stmt.executeBatch();

        ResultSet rs = stmt.executeQuery("SELECT * FROM STORES");

        System.out.println("Table STORES after insertion:");
        System.out.println("STORE_NO  LOCATION          COF_TYPE     MGR");
        while (rs.next()) {
            int storeNo = rs.getInt("STORE_NO");
            Struct location = (Struct) rs.getObject("LOCATION");
            Object[] locAttrs = location.getAttributes();
            Array coffeeTypes = rs.getArray("COF_TYPE");
            String[] cofTypes = (String[]) coffeeTypes.getArray();

            Ref managerRef = rs.getRef("MGR");
            PreparedStatement pstmt = con.prepareStatement("SELECT MANAGER FROM MANAGERS WHERE OID = ?");
            pstmt.setRef(1, managerRef);
            ResultSet rs2 = pstmt.executeQuery();
            rs2.next();
            Struct manager = (Struct) rs2.getObject("MANAGER");
            Object[] manAttrs = manager.getAttributes();

            System.out.print(storeNo + "   ");
            System.out.print(locAttrs[0] + " " + locAttrs[1] + " " + locAttrs[2] + ", " + locAttrs[3] + "  "
                    + locAttrs[4] + " ");
            for (int i = 0; i < cofTypes.length; i++)
                System.out.print(cofTypes[i] + " ");
            System.out.println(manAttrs[1] + ", " + manAttrs[2]);

            rs2.close();
            pstmt.close();
        }

        rs.close();
        stmt.close();
        con.close();

    } catch (BatchUpdateException b) {
        System.err.println("-----BatchUpdateException-----");
        System.err.println("SQLState:  " + b.getSQLState());
        System.err.println("Message:  " + b.getMessage());
        System.err.println("Vendor:  " + b.getErrorCode());
        System.err.print("Update counts:  ");
        int[] updateCounts = b.getUpdateCounts();
        for (int i = 0; i < updateCounts.length; i++) {
            System.err.print(updateCounts[i] + "   ");
        }
        System.err.println("");

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Message:  " + ex.getMessage());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:Main.java

public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;/*  w w  w  . ja  va2 s. co  m*/
    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());
    }
}