Example usage for java.sql ResultSetMetaData getColumnName

List of usage examples for java.sql ResultSetMetaData getColumnName

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnName.

Prototype

String getColumnName(int column) throws SQLException;

Source Link

Document

Get the designated column's name.

Usage

From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java

/**
 * Similar to the same method in original pubtest utility, but doesn't throw an exception if 0 rows are returned
 * and uses existing(established) JDBC connection corresponding to its published datasource name.
 * //  w  w w . j a v a2 s .c o m
 * @param item
 * 
 * @return result - A string containing a formatted response with the rows and first row latency:  <rows>:<firstRowLatency>
 */
public static String executeQuery(RegressionItem item, HashMap<String, Connection> cisConnections,
        String outputFile, String delimiter, String printOutputType) throws CompositeException {
    // Set the command and action name
    String command = "executeQuery";
    String actionName = "REGRESSION_TEST";

    int rows = 0;
    String result = null;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    start = System.currentTimeMillis();
    long firstRowLatency = 0L;

    // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
    if (CommonUtils.isExecOperation()) {
        try {
            conn = getJdbcConnection(item.database, cisConnections); // don't need to check for null here.

            String URL = null;
            String userName = null;
            if (conn.getMetaData() != null) {
                if (conn.getMetaData().getURL() != null)
                    URL = conn.getMetaData().getURL();
                if (conn.getMetaData().getUserName() != null)
                    userName = conn.getMetaData().getUserName();
            }
            RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                    "RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delimiter, printOutputType).  item.database="
                            + item.database + "  cisConnections.URL=" + URL + "  cisConnections.userName="
                            + userName + "  outputFile=" + outputFile + "  delimiter=" + delimiter
                            + "  printOutputType=" + printOutputType,
                    "");
            RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                    "DEBUG: connection to DB successful", "");

            stmt = conn.createStatement();
            stmt.execute(item.input.replaceAll("\n", " "));
            rs = stmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columns = rsmd.getColumnCount();
            RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                    "DEBUG: number metadata columns=" + columns, "");

            // Get the column metadata           
            boolean addSep = false;
            String content = "";
            RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: Get column metadata.", "");
            for (int i = 0; i < columns; i++) {
                if (addSep) {
                    content += delimiter;
                }
                if (rsmd.getColumnName(i + 1) != null)
                    content += rsmd.getColumnName(i + 1).toString();
                else
                    content += "";
                addSep = true;
            }
            if (outputFile != null)
                CommonUtils.appendContentToFile(outputFile, content);
            RegressionManagerUtils.printOutputStr(printOutputType, "results", content, "");

            // Read the values
            boolean firstRow = true;
            RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: Begin Query Loop.", "");
            while (rs.next()) {
                if (firstRow) {
                    firstRowLatency = System.currentTimeMillis() - start;
                    firstRow = false;
                    RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                            "DEBUG: Set first row latency time=" + firstRowLatency, "");
                }
                addSep = false;
                content = "";
                for (int i = 0; i < columns; i++) {
                    if (addSep) {
                        content += delimiter;
                    }
                    if (rs.getObject(i + 1) != null)
                        content += rs.getObject(i + 1).toString();
                    else
                        content += "";
                    addSep = true;
                }
                if (outputFile != null)
                    CommonUtils.appendContentToFile(outputFile, content);
                RegressionManagerUtils.printOutputStr(printOutputType, "results", content, "");

                rows++;
            }
        } catch (SQLException e) {
            RegressionManagerUtils.printOutputStr(printOutputType, "debug",
                    "DEBUG: Exception caught in RegressionManagerUtils.executeQuery:", "");
            RegressionManagerUtils.printOutputStr(printOutputType, "debug", e.getMessage(), "");
            throw new CompositeException("executeQuery(): " + e.getMessage());
        }

        finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                rs = null;
                stmt = null;
                throw new CompositeException(
                        "executeQuery(): unable to close ResultSet or Statement" + e.getMessage());
            }
        }
        RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeQuery()", "");
    } else {
        logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                + "] WAS NOT PERFORMED.\n");
    }

    // <rows>:<firstRowLatency>
    result = "" + rows + ":" + firstRowLatency;
    return result;
    /* Note: to process this result string on the client invocation side use the following pattern:
     * 
     *    String result = RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delim, printOutputType, "results");
       String results[] = result.split(":");
       if (results.length > 1) {
          rowCount = Integer.valueOf(results[0]);
             firstRowLatency.addAndGet(Long.parseLong(results[1]));                    
       }                  
     */
}

From source file:edu.ku.brc.specify.toycode.RegPivot.java

/**
 * @param newTblName//  w  w w  .  ja v  a 2 s  . c o m
 * @param tblName
 * @param keyName
 */
private void process(final String newTblName, final String tblName, final String keyName, final String defSQL,
        final String fillSQL, final boolean isRegBuild) {

    String sql = String.format("SELECT DISTINCT Name FROM %s", tblName);
    String sql2 = "SELECT MAX(LENGTH(Value)) FROM " + tblName + " WHERE Name = '%s'";

    int instCnt = 0;

    Statement stmt = null;
    try {
        stmt = connection.createStatement();

        BasicSQLUtils.setDBConnection(connection);

        boolean doBuild = true;

        if (doBuild) {
            StringBuilder tblSQL = new StringBuilder(String
                    .format("CREATE TABLE %s (`%s` INT(11) NOT NULL AUTO_INCREMENT, \n", newTblName, keyName));

            Vector<String> dbFieldNames = new Vector<String>();
            Vector<Integer> dbFieldTypes = new Vector<Integer>();

            if (defSQL != null) {
                ResultSet rs = stmt.executeQuery(defSQL);
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    if (i > 1)
                        tblSQL.append(",\n ");

                    String name = rsmd.getColumnName(i);
                    dbFieldNames.add(rsmd.getColumnName(i));
                    dbFieldTypes.add(rsmd.getColumnType(i));
                    switch (rsmd.getColumnType(i)) {
                    case java.sql.Types.INTEGER:
                        tblSQL.append(String.format("`%s` INT(11) DEFAULT NULL", name));
                        break;

                    case java.sql.Types.VARCHAR:
                        tblSQL.append(String.format("`%s` VARCHAR(%s) DEFAULT NULL", name, 64));
                        break;

                    case java.sql.Types.TIMESTAMP:
                        tblSQL.append(String.format("`%s` DATETIME DEFAULT NULL", name));
                        break;

                    default:
                        System.err.println(String.format("No case for %s %d", name, rsmd.getColumnType(i)));
                        break;
                    }
                }
                rs.close();
            }

            int secInx = dbFieldNames.size() + 1;

            System.out.println("secInx: " + secInx + "  " + tblSQL.toString());

            HashSet<String> nameSet = new HashSet<String>();

            int cnt = 0;
            for (Object nmObj : BasicSQLUtils.querySingleCol(connection, sql)) {
                String name = nmObj.toString();

                if (name.endsWith("ID")) {
                    continue;
                }

                name = StringUtils.replace(name, "(", "_");
                name = StringUtils.replace(name, ")", "_");

                if (nameSet.contains(name))
                    continue;

                nameSet.add(name);

                tblSQL.append(",\n ");

                if (name.startsWith("num_") || name.startsWith("Usage_")) {
                    tblSQL.append(String.format("`%s` INT(11) DEFAULT NULL", name));
                    dbFieldNames.add(name);
                    dbFieldTypes.add(java.sql.Types.INTEGER);

                } else if (name.endsWith("_number")) {
                    tblSQL.append(String.format("`%s` VARCHAR(16) DEFAULT NULL", name));
                    dbFieldNames.add(name);
                    dbFieldTypes.add(java.sql.Types.VARCHAR);

                } else {
                    int maxLen = BasicSQLUtils.getCountAsInt(connection, String.format(sql2, name));
                    tblSQL.append(String.format("`%s` VARCHAR(%s) DEFAULT NULL", name, maxLen + 1));
                    dbFieldNames.add(name);
                    dbFieldTypes.add(java.sql.Types.VARCHAR);
                }
                cnt++;
            }

            if (isRegBuild) {
                tblSQL.append(String.format(",\n`RecordType`INT(11) DEFAULT NULL"));
            }
            tblSQL.append(String.format(",\n PRIMARY KEY (`%s`)) ENGINE=InnoDB DEFAULT CHARSET=UTF8", keyName));

            System.out.println(tblSQL.toString());

            DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
            dbMgr.setConnection(connection);
            if (dbMgr.doesDBHaveTable(newTblName)) {
                BasicSQLUtils.update(connection, "DROP TABLE " + newTblName);
            }
            BasicSQLUtils.update(connection, tblSQL.toString());

            HashMap<Integer, String> inxToName = new HashMap<Integer, String>();

            StringBuilder fields = new StringBuilder();
            StringBuilder vals = new StringBuilder();
            int inx = 0;
            for (String nm : dbFieldNames) {
                if (fields.length() > 0)
                    fields.append(",");
                fields.append(nm);

                if (vals.length() > 0)
                    vals.append(",");
                vals.append('?');

                inxToName.put(inx, nm);
                inx++;
            }

            if (isRegBuild) {
                if (fields.length() > 0)
                    fields.append(",");
                fields.append("RecordType");

                if (vals.length() > 0)
                    vals.append(",");
                vals.append('?');
            }

            String insertSQL = String.format("INSERT INTO %s (%s) VALUES(%s)", newTblName, fields.toString(),
                    vals.toString());
            System.out.println(insertSQL);

            PreparedStatement pStmt = connection.prepareStatement(insertSQL);

            if (isRegBuild) {
                fillRegisterTable(newTblName, stmt, pStmt, fillSQL, secInx, dbFieldTypes, dbFieldNames,
                        inxToName);
            } else {
                fillTrackTable(newTblName, stmt, pStmt, fillSQL, secInx, dbFieldTypes, dbFieldNames, inxToName);
            }

            System.out.println("InstCnt: " + instCnt);
            pStmt.close();
        }

        boolean doIP = false;
        if (doIP) {
            HTTPGetter httpGetter = new HTTPGetter();

            sql = "SELECT RegID, IP from reg";
            PreparedStatement pStmt = connection.prepareStatement(String
                    .format("UPDATE %s SET lookup=?, Country=?, City=? WHERE %s = ?", newTblName, keyName));

            HashMap<String, String> ipHash = new HashMap<String, String>();
            HashMap<String, Pair<String, String>> ccHash = new HashMap<String, Pair<String, String>>();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                int regId = rs.getInt(1);
                String ip = rs.getString(2);

                String hostName = ipHash.get(ip);
                String country = null;
                String city = null;
                if (hostName == null) {
                    String rvStr = new String(
                            httpGetter.doHTTPRequest("http://api.hostip.info/get_html.php?ip=" + ip));
                    country = parse(rvStr, "Country:");
                    city = parse(rvStr, "City:");
                    System.out.println(rvStr + "[" + country + "][" + city + "]");

                    try {
                        InetAddress addr = InetAddress.getByName(ip);
                        hostName = addr.getHostName();
                        ipHash.put(ip, hostName);
                        ccHash.put(ip, new Pair<String, String>(country, city));

                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                } else {
                    Pair<String, String> p = ccHash.get(ip);
                    if (p != null) {
                        country = p.first;
                        city = p.second;
                    }
                }

                pStmt.setString(1, hostName);
                pStmt.setString(2, country);
                pStmt.setString(3, city);
                pStmt.setInt(4, regId);
                pStmt.executeUpdate();
            }
            pStmt.close();
        }

        stmt.close();
        colDBConn.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    System.out.println("Done.");
}

From source file:org.apache.sqoop.manager.SqlManager.java

/**
 * Get column types for a query statement that we do not modify further.
 *//*w w w  .  j  a  va 2 s  . c om*/
protected Map<String, Integer> getColumnTypesForRawQuery(String stmt) {
    ResultSet results;
    try {
        results = execute(stmt);
    } catch (SQLException sqlE) {
        LOG.error("Error executing statement: " + sqlE.toString(), sqlE);
        release();
        return null;
    }

    try {
        Map<String, Integer> colTypes = new SqlTypeMap<String, Integer>();

        int cols = results.getMetaData().getColumnCount();
        ResultSetMetaData metadata = results.getMetaData();
        for (int i = 1; i < cols + 1; i++) {
            int typeId = metadata.getColumnType(i);
            // If we have an unsigned int we need to make extra room by
            // plopping it into a bigint
            if (typeId == Types.INTEGER && !metadata.isSigned(i)) {
                typeId = Types.BIGINT;
            }

            String colName = metadata.getColumnName(i);
            if (colName == null || colName.equals("")) {
                colName = metadata.getColumnLabel(i);
            }

            colTypes.put(colName, Integer.valueOf(typeId));
        }

        return colTypes;
    } catch (SQLException sqlException) {
        LOG.error("Error reading from database: " + sqlException.toString());
        return null;
    } finally {
        try {
            results.close();
            getConnection().commit();
        } catch (SQLException sqlE) {
            LOG.warn("SQLException closing ResultSet: " + sqlE.toString());
        }

        release();
    }
}

From source file:org.dspace.storage.rdbms.DatabaseManager.java

/**
 * Convert the current row in a ResultSet into a TableRow object.
 *
 * @param results/*from   w w  w  .  j av a  2 s  .  c o m*/
 *            A ResultSet to process
 * @param table
 *            The name of the table
 * @param pColumnNames
 *            The name of the columns in this resultset
 * @return A TableRow object with the data from the ResultSet
 * @exception SQLException
 *                If a database error occurs
 */
static TableRow process(ResultSet results, String table, List<String> pColumnNames) throws SQLException {
    ResultSetMetaData meta = results.getMetaData();
    int columns = meta.getColumnCount() + 1;

    // If we haven't been passed the column names try to generate them from the metadata / table
    List<String> columnNames = pColumnNames != null ? pColumnNames
            : ((table == null) ? getColumnNames(meta) : getColumnNames(table));

    TableRow row = new TableRow(canonicalize(table), columnNames);

    // Process the columns in order
    // (This ensures maximum backwards compatibility with
    // old JDBC drivers)
    for (int i = 1; i < columns; i++) {
        String name = meta.getColumnName(i);
        int jdbctype = meta.getColumnType(i);

        switch (jdbctype) {
        case Types.BIT:
            row.setColumn(name, results.getBoolean(i));
            break;

        case Types.INTEGER:
        case Types.NUMERIC:
            if (isOracle) {
                long longValue = results.getLong(i);
                if (longValue <= (long) Integer.MAX_VALUE) {
                    row.setColumn(name, (int) longValue);
                } else {
                    row.setColumn(name, longValue);
                }
            } else {
                row.setColumn(name, results.getInt(i));
            }
            break;

        case Types.DECIMAL:
        case Types.BIGINT:
            row.setColumn(name, results.getLong(i));
            break;

        case Types.DOUBLE:
            row.setColumn(name, results.getDouble(i));
            break;

        case Types.CLOB:
            if (isOracle) {
                row.setColumn(name, results.getString(i));
            } else {
                throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype);
            }
            break;

        case Types.VARCHAR:
            try {
                byte[] bytes = results.getBytes(i);

                if (bytes != null) {
                    String mystring = new String(results.getBytes(i), "UTF-8");
                    row.setColumn(name, mystring);
                } else {
                    row.setColumn(name, results.getString(i));
                }
            } catch (UnsupportedEncodingException e) {
                log.error("Unable to parse text from database", e);
            }
            break;

        case Types.DATE:
            row.setColumn(name, results.getDate(i));
            break;

        case Types.TIME:
            row.setColumn(name, results.getTime(i));
            break;

        case Types.TIMESTAMP:
            row.setColumn(name, results.getTimestamp(i));
            break;

        default:
            throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype);
        }

        // Determines if the last column was null, and sets the tablerow accordingly
        if (results.wasNull()) {
            row.setColumnNull(name);
        }
    }

    // Now that we've prepped the TableRow, reset the flags so that we can detect which columns have changed
    row.resetChanged();
    return row;
}

From source file:org.cloudgraph.rdb.service.JDBCSupport.java

protected List<List<PropertyPair>> fetch(PlasmaType type, StringBuilder sql, Set<Property> props,
        Object[] params, Connection con) {
    List<List<PropertyPair>> result = new ArrayList<List<PropertyPair>>();
    PreparedStatement statement = null;
    ResultSet rs = null;//from  w w w.  ja  va  2s .com
    try {
        if (log.isDebugEnabled()) {
            if (params == null || params.length == 0) {
                log.debug("fetch: " + sql.toString());
            } else {
                StringBuilder paramBuf = new StringBuilder();
                paramBuf.append(" [");
                for (int p = 0; p < params.length; p++) {
                    if (p > 0)
                        paramBuf.append(", ");
                    paramBuf.append(String.valueOf(params[p]));
                }
                paramBuf.append("]");
                log.debug("fetch: " + sql.toString() + " " + paramBuf.toString());
            }
        }
        statement = con.prepareStatement(sql.toString(), ResultSet.TYPE_FORWARD_ONLY, /*
                                                                                       * ResultSet
                                                                                       * .
                                                                                       * TYPE_SCROLL_INSENSITIVE
                                                                                       * ,
                                                                                       */
                ResultSet.CONCUR_READ_ONLY);

        for (int i = 0; i < params.length; i++)
            statement.setString(i + 1, // FIXME
                    String.valueOf(params[i]));

        statement.execute();
        rs = statement.getResultSet();
        ResultSetMetaData rsMeta = rs.getMetaData();
        int numcols = rsMeta.getColumnCount();

        int count = 0;
        while (rs.next()) {
            List<PropertyPair> row = new ArrayList<PropertyPair>(numcols);
            result.add(row);
            for (int i = 1; i <= numcols; i++) {
                String columnName = rsMeta.getColumnName(i);
                int columnType = rsMeta.getColumnType(i);
                PlasmaProperty prop = (PlasmaProperty) type.getProperty(columnName);
                PlasmaProperty valueProp = prop;
                while (!valueProp.getType().isDataType()) {
                    valueProp = getOppositePriKeyProperty(valueProp);
                }
                Object value = converter.fromJDBCDataType(rs, i, columnType, valueProp);
                if (value != null) {
                    PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value);
                    if (!valueProp.equals(prop))
                        pair.setValueProp(valueProp);
                    if (!props.contains(prop))
                        pair.setQueryProperty(false);
                    row.add(pair);
                }
            }
            count++;
        }
        if (log.isDebugEnabled())
            log.debug("returned " + count + " results");
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:org.dspace.storage.rdbms.MockDatabaseManager.java

/**
 * Convert the current row in a ResultSet into a TableRow object.
 *
 * @param results//from  w  w  w .jav a 2s  .  com
 *            A ResultSet to process
 * @param table
 *            The name of the table
 * @param pColumnNames
 *            The name of the columns in this resultset
 * @return A TableRow object with the data from the ResultSet
 * @exception SQLException
 *                If a database error occurs
 */
@Mock
static TableRow process(ResultSet results, String table, List<String> pColumnNames) throws SQLException {
    String dbName = ConfigurationManager.getProperty("db.name");
    ResultSetMetaData meta = results.getMetaData();
    int columns = meta.getColumnCount() + 1;

    // If we haven't been passed the column names try to generate them from the metadata / table
    List<String> columnNames = pColumnNames != null ? pColumnNames
            : ((table == null) ? getColumnNames(meta) : getColumnNames(table));

    TableRow row = new TableRow(canonicalize(table), columnNames);

    // Process the columns in order
    // (This ensures maximum backwards compatibility with
    // old JDBC drivers)
    for (int i = 1; i < columns; i++) {
        String name = meta.getColumnName(i);
        int jdbctype = meta.getColumnType(i);

        if (jdbctype == Types.BIT || jdbctype == Types.BOOLEAN) {
            row.setColumn(name, results.getBoolean(i));
        } else if ((jdbctype == Types.INTEGER) || (jdbctype == Types.NUMERIC) || (jdbctype == Types.DECIMAL)) {
            // If we are using oracle
            if ("oracle".equals(dbName)) {
                // Test the value from the record set. If it can be represented using an int, do so.
                // Otherwise, store it as long
                long longValue = results.getLong(i);
                if (longValue <= (long) Integer.MAX_VALUE)
                    row.setColumn(name, (int) longValue);
                else
                    row.setColumn(name, longValue);
            } else
                row.setColumn(name, results.getInt(i));
        } else if (jdbctype == Types.BIGINT) {
            row.setColumn(name, results.getLong(i));
        } else if (jdbctype == Types.DOUBLE) {
            row.setColumn(name, results.getDouble(i));
        } else if (jdbctype == Types.CLOB && "oracle".equals(dbName)) {
            // Support CLOBs in place of TEXT columns in Oracle
            row.setColumn(name, results.getString(i));
        } else if (jdbctype == Types.VARCHAR) {
            /*try
            {
            byte[] bytes = results.getBytes(i);
                    
            if (bytes != null)
            {
                String mystring = new String(results.getBytes(i),
                        "UTF-8");
                row.setColumn(name, mystring);
            }
            else
            {
                row.setColumn(name, results.getString(i));
            }
                    
            }
            catch (UnsupportedEncodingException e)
            {
            // do nothing, UTF-8 is built in!
            }*/
            //removing issue with H2 and getBytes
            row.setColumn(name, results.getString(i));
        } else if (jdbctype == Types.DATE) {
            row.setColumn(name, results.getDate(i));
        } else if (jdbctype == Types.TIME) {
            row.setColumn(name, results.getTime(i));
        } else if (jdbctype == Types.TIMESTAMP) {
            row.setColumn(name, results.getTimestamp(i));
        } else {
            throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype + " (" + name + ")");
        }

        if (results.wasNull()) {
            row.setColumnNull(name);
        }
    }

    // Now that we've prepped the TableRow, reset the flags so that we can detect which columns have changed
    row.resetChanged();
    return row;
}

From source file:gr.seab.r2rml.beans.Generator.java

BaseDatatype findFieldDataType(String field, ResultSet rs) {
    field = field.trim();//from w ww.  j av a  2  s .c  o m
    if (verbose)
        log.info("Figuring out datatype of field: " + field);
    try {
        ResultSetMetaData rsMeta = rs.getMetaData();
        if (verbose)
            log.info("Table name " + rsMeta.getTableName(1));
        for (int i = 1; i <= rsMeta.getColumnCount(); i++) {
            if (verbose)
                log.info("Column name is " + rsMeta.getColumnName(i));
            if (rsMeta.getColumnName(i).equals(field)) {
                String sqlType = rsMeta.getColumnTypeName(i);
                if (verbose)
                    log.info(
                            "Column " + i + " with name " + rsMeta.getColumnName(i) + " is of type " + sqlType);
                return util.findDataTypeFromSql(sqlType);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:migration.Helper.java

/**
 * Print a table row to stdout./*www . j av a2  s  .com*/
 * 
 * @param rs
 *            the rs
 * @param only
 *            only one attribute?
 * @param show
 *            the only or last attribute number to be displayed
 * @throws SQLException
 *             the sQL exception
 */
void printTableRow(final ResultSet rs, final boolean only, final int show) throws SQLException {
    // get result set meta data
    final ResultSetMetaData rsMetaData = rs.getMetaData();
    final int numberOfColumns = rsMetaData.getColumnCount();
    final String[] names = new String[numberOfColumns];
    // get the column names; column indexes start from 1
    for (int i = 0; i < numberOfColumns; i++) {
        names[i] = rsMetaData.getColumnName(i + 1);
    }
    final String tmp;
    for (int i = 0; i < numberOfColumns; i++) {
        if (((show >= (i + 1)) && !only) || (only && (show == (i + 1)))) {
            System.out.println(names[i] + " " + rs.getString(i + 1));
        }
    }
    System.out.println(" ");
    System.out.println("----------------------------------------------------------------------");
    System.out.println(" ");
}

From source file:com.googlecode.fascinator.portal.services.impl.DatabaseServicesImpl.java

/**
 * Parse the results of the query into a basic Java data structure. Users
 * wanting the original result set should call getResultSet() directly
 * against the prepared statement.//from w ww .  ja  va2 s  . co  m
 * 
 * @param sql The prepared statement to get the results from.
 * @return List<Map<String, String>> A list of result rows as key/value
 *         pairs in HashMaps
 * @throws Exception if there is an error.
 */
@Override
public List<Map<String, String>> getResults(PreparedStatement sql) throws Exception {
    // Prepare variables
    List<Map<String, String>> response = new ArrayList<Map<String, String>>();
    ResultSet results = null;
    ResultSetMetaData columns = null;

    try {
        // Run the search
        results = sql.executeQuery();
        // Process the results
        columns = results.getMetaData();
        if (results.isClosed()) {
            log.error("!!! ResultSet is closed");
            return response;
        }
        while (results.next()) {
            Map<String, String> row = new HashMap<String, String>();
            for (int i = 1; i <= columns.getColumnCount(); i++) {
                // log.debug("getResults(): Storing '{}' ({}) => " +
                // results.getString(i), columns.getColumnName(i),
                // columns.getColumnLabel(i));
                row.put(columns.getColumnName(i), results.getString(i));
            }
            response.add(row);
        }
        // Finish up
        results.close();
        return response;

    } catch (SQLException ex) {
        throw new Exception("Error executing query:", ex);
    }
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static Document addResultSetXmlPart(Element resultsElement, ResultSet rs, Document xmlDocumentResult)
        throws SQLException {
    // resultSet = statement.getResultSet();
    // connection to an ACCESS MDB
    ResultSetMetaData rsmd = rs.getMetaData();
    Element resultSetElement = xmlDocumentResult.createElement("ResultSet");

    resultSetElement.setAttribute("fetchSize", String.valueOf(rs.getFetchSize()));
    resultsElement.appendChild(resultSetElement);

    int colCount = rsmd.getColumnCount();
    while (rs.next()) {
        Element rowElement = xmlDocumentResult.createElement("Row");
        rowElement.setAttribute("rowNumber", String.valueOf(rs.getRow()));

        resultsElement.appendChild(rowElement);
        for (int ii = 1; ii <= colCount; ii++) {
            String columnName = "";
            if (!StringUtils.isBlank(rsmd.getTableName(ii))) {
                columnName += (rsmd.getTableName(ii)).toUpperCase() + ".";
            }/*from w  w w.j  av a 2s  . co m*/
            columnName += (rsmd.getColumnName(ii)).toUpperCase();
            String value = rs.getString(ii);
            Element node = xmlDocumentResult.createElement(createXmlName(columnName));
            if (!StringUtils.isBlank(value)) {
                Text textNode = xmlDocumentResult.createTextNode(value.toString());
                node.appendChild(textNode);
            }
            rowElement.appendChild(node);
        }
        resultSetElement.appendChild(rowElement);
    }
    return xmlDocumentResult;
}