Example usage for java.sql ResultSet getMetaData

List of usage examples for java.sql ResultSet getMetaData

Introduction

In this page you can find the example usage for java.sql ResultSet getMetaData.

Prototype

ResultSetMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves the number, types and properties of this ResultSet object's columns.

Usage

From source file:com.espertech.esperio.db.SupportDatabaseService.java

public static Object[][] readAll(String tableName) throws SQLException {
    Connection connection = getConnection(PARTURL, DBUSER, DBPWD);
    connection.setAutoCommit(true);//w  ww .  j a va 2s  .c om
    Statement stmt = connection.createStatement();
    String sql = "select * from " + tableName;
    log.info("Executing sql : " + sql);
    ResultSet resultSet = stmt.executeQuery(sql);

    List<Object[]> rows = new ArrayList<Object[]>();
    while (resultSet.next()) {
        List<Object> row = new ArrayList<Object>();
        for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
            row.add(resultSet.getObject(i + 1));
        }
        rows.add(row.toArray());
    }

    Object[][] arr = new Object[rows.size()][];
    for (int i = 0; i < rows.size(); i++) {
        arr[i] = rows.get(i);
    }

    stmt.close();
    connection.close();
    return arr;
}

From source file:com.cloudera.impala.testutil.ImpalaJdbcClient.java

/**
 * Executes one or more queries using the given ImpalaJdbcClient. Multiple queries
 * should be seperated using semi-colons.
 * @throws SQLException//from  w  w  w  . ja v  a  2 s .  c  o m
 */
private static void execQuery(ImpalaJdbcClient client, String queryString)
        throws SQLException, NumberFormatException {

    String[] queries = queryString.trim().split(";");
    for (String query : queries) {
        query = query.trim();
        if (query.indexOf(" ") > -1) {
            if (query.substring(0, query.indexOf(" ")).equalsIgnoreCase("use")) {
                String[] split_query = query.split(" ");
                String db_name = split_query[split_query.length - 1];
                client.changeDatabase(db_name);
                client.getStatement().close();
                continue;
            }
        }
        long startTime = System.currentTimeMillis();
        ResultSet res = client.execQuery(query);
        ResultSetMetaData meta = res.getMetaData();
        ArrayList<String> arrayList = Lists.newArrayList();

        // This token (and the [END] token) are used to help parsing the result output
        // for test verification purposes.
        LOG.info("----[START]----");
        int rowCount = 0;
        while (res.next()) {
            arrayList.clear();
            for (int i = 1; i <= meta.getColumnCount(); ++i) {
                // Format the value based on the column type
                String colVal = formatColumnValue(res.getString(i), meta.getColumnTypeName(i));
                arrayList.add(colVal);
            }
            LOG.info(Joiner.on(",").join(arrayList));
            ++rowCount;
        }
        LOG.info("----[END]----");
        long endTime = System.currentTimeMillis();
        float seconds = (endTime - startTime) / 1000F;
        LOG.info("Returned " + rowCount + " row(s) in " + seconds + "s");

        // TODO: To work around a JDBC driver issue (CDH-10035), make sure the Statement
        // is closed after every query.
        client.getStatement().close();
    }
}

From source file:it.alidays.mapengine.codegenerator.MapperEngineCodeGenerator.java

private static void manageRetrieve(Retrieve retrieve, Connection connection, String packageName,
        File destinationDir)// w w w  . j a  va2  s  . c o  m
        throws SQLException, JClassAlreadyExistsException, IOException, MapperEngineCodeGeneratorException {
    logger.info("Generating map for {}", retrieve.getId());

    int vuidCount = RetrieveHandler.getVuidCount(retrieve.getContent());
    String content = retrieve.getContent().replaceAll(RetrieveHandler.VUID_KEY, "?");

    Map<String, Integer> columns = new LinkedHashMap<>();

    logger.info("\tRetrieving columns' name");
    try (PreparedStatement preparedStatement = connection.prepareStatement(content)) {
        for (int index = 1; index <= vuidCount; index++) {
            preparedStatement.setObject(index, "_");
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        for (int i = 1, n = resultSetMetaData.getColumnCount(); i <= n; i++) {
            String columnName = Utils.arrangeColumnName(resultSetMetaData.getColumnLabel(i));
            Integer columnType = resultSetMetaData.getColumnType(i);
            columns.put(columnName, columnType);
        }
    }
    logger.info("\tRetrieved {} columns' name", columns.size());

    createMapClass(retrieve, columns, packageName, destinationDir);
    createRetrieveClass(retrieve, packageName, destinationDir);

    logger.info("Map successfully generated for {}", retrieve.getId());
}

From source file:eagle.storage.jdbc.entity.JdbcEntitySerDeserHelper.java

/**
 *
 * @param resultSet/*from w w  w . j  a v  a 2  s.co m*/
 * @param entityDefinition
 * @return
 * @throws SQLException
 * @throws IOException
 */
public static Map<String, Object> readInternal(ResultSet resultSet, JdbcEntityDefinition entityDefinition)
        throws SQLException, IOException {
    ResultSetMetaData metadata = resultSet.getMetaData();
    int columnCount = metadata.getColumnCount();
    Map<String, Object> row = new HashMap<String, Object>();
    for (int i = 1; i <= columnCount; i++) {
        String columnName = metadata.getColumnName(i);
        JdbcSerDeser serDeser = entityDefinition.getJdbcSerDeser(columnName);
        if (serDeser == null) {
            throw new IOException("SQLSerDeser for column: " + columnName + " is null");
        }
        Object value = serDeser.readValue(resultSet, columnName, entityDefinition);
        row.put(columnName, value);
    }
    return row;
}

From source file:com.thoughtworks.go.server.database.DatabaseFixture.java

public static Object[][] query(String query, H2Database h2Database) {
    BasicDataSource source = h2Database.createDataSource();
    Connection con = null;/*from   w w  w  . j a v  a  2 s  .  com*/
    Statement stmt = null;
    ResultSet rs = null;
    try {
        con = source.getConnection();
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        int columnCount = rs.getMetaData().getColumnCount();
        List<Object[]> objects = new ArrayList<>();
        while (rs.next()) {
            Object[] values = new Object[columnCount];
            for (int i = 0; i < values.length; i++) {
                values[i] = rs.getObject(i + 1);
            }
            objects.add(values);
        }
        return objects.toArray(new Object[0][0]);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            assert stmt != null;
            stmt.close();
            con.close();
            assert rs != null;
            rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:ProxyAuthTest.java

private static void runQuery(String sqlStmt) throws Exception {
    Statement stmt = con.createStatement();
    ResultSet res = stmt.executeQuery(sqlStmt);

    ResultSetMetaData meta = res.getMetaData();
    System.out.println("Resultset has " + meta.getColumnCount() + " columns");
    for (int i = 1; i <= meta.getColumnCount(); i++) {
        System.out.println(/*from   w w w  .  j  ava 2 s . co  m*/
                "Column #" + i + " Name: " + meta.getColumnName(i) + " Type: " + meta.getColumnType(i));
    }

    while (res.next()) {
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            System.out.println("Column #" + i + ": " + res.getString(i));
        }
    }
    res.close();
    stmt.close();
}

From source file:io.cloudslang.content.database.utils.Format.java

/**
 * Returns tabular form of resultSet similar to what you would get from
 * running a query from the command line
 *
 * @param result populated result set//from   w w  w  . ja v  a  2 s.  c  o  m
 * @param cal    calendar to use to format
 * @return
 * @throws SQLException
 */
private static String resultSetToTable(ResultSet result, Calendar cal, boolean checkNullTermination)
        throws SQLException {
    assert (result != null);

    ResultSetMetaData md = result.getMetaData();
    int nCols = md.getColumnCount();
    String[] headers = new String[nCols];
    int[] headerSz = new int[nCols]; // Note: Eclipse has a friendly getDisplaySizes() function
    int maxWidth = 1; // maximum column width - initially set at 1 to prevent an edge case

    List<String[]> rows = new ArrayList<>(); // columns
    // This is fairly space intensive because we don't want to turn this into an O^2(n) problem
    // instead of a O(n) problem. It's O(n) space but with a k of 2, and same with space.
    // Ugh, stupid time-memory tradeoffs
    // We're storing it ALL in Java data structures to figure out width of columns first, then padding later
    // for serialization
    for (int colheader = 0; colheader < nCols; colheader++) {
        headers[colheader] = md.getColumnLabel(colheader + 1);
        headerSz[colheader] = headers[colheader].length();
    }

    // setup columns to be width of column labels
    while (result.next()) {
        String[] row = new String[headers.length];
        for (int colN = 0; colN < nCols; colN++) {
            String colVal = getColumn(result, colN + 1, checkNullTermination);
            headerSz[colN] = colVal.length() > headerSz[colN] ? colVal.length() : headerSz[colN];
            row[colN] = colVal;
        }
        rows.add(row);
    }
    // column widths set, now start populating the string builder
    StringBuilder resultSb = new StringBuilder(headers.length * maxWidth / 2);
    // construct the headers
    for (int colheader = 0; colheader < nCols; colheader++) {
        resultSb.append(headers[colheader]);
        for (int count = 0; count < headerSz[colheader] - headers[colheader].length() + colPadding; count++)
            resultSb.append(" ");
    }
    resultSb.append(NEW_LINE);
    for (int colheader = 0; colheader < nCols; colheader++) {
        for (int count = 0; count < headerSz[colheader]; count++)
            resultSb.append("-");
        for (int count = 0; count < colPadding; count++)
            resultSb.append(" ");
    }
    resultSb.append(NEW_LINE);
    // now append the data itself
    for (String[] row : rows) {
        for (int col = 0; col < nCols; col++) {
            resultSb.append(row[col]);
            for (int padIdx = 0; padIdx < headerSz[col] - row[col].length() + colPadding; padIdx++)
                resultSb.append(" ");
        }
        resultSb.append(NEW_LINE);
    }

    return resultSb.toString();
}

From source file:ca.sqlpower.persistance.CatNap.java

public static void load(Connection con, String tableName, Object loadTo, String where)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException {
    BeanUtils.describe(loadTo);/*w ww . jav a 2s. c o  m*/
    Statement stmt = null;
    StringBuffer sql = new StringBuffer();
    try {
        sql.append("SELECT * FROM " + tableName + " WHERE " + where);
        sql.append("\n");

        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql.toString());
        while (rs.next()) {
            ResultSetMetaData metaData = rs.getMetaData();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String beanPropertyName = underscoreToCamelCaps(metaData.getColumnName(i).toLowerCase());

                BeanUtils.setProperty(loadTo, beanPropertyName, rs.getObject(i));

            }
        }
    } catch (SQLException ex) {
        System.err.println("Catnap: Insert failed. Statement was:\n" + sql);
        throw ex;
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException ex) {
            System.err.println(
                    "Catnap: Couldn't close the statement.  Damn.  But at least you won a stack trace:");
            ex.printStackTrace();
        }
    }
}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create xml string - fastest, but may have encoding issues
 *
 * @param rs - a Result set//from  w  w  w  .  j  av  a 2s . c o  m
 * @return - XML string of a result set
 * @throws SQLException - If error when read data from database
 */
public static String toXML(ResultSet rs) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();
    StringBuilder xml = new StringBuilder();
    xml.append("<Results>");

    while (rs.next()) {
        xml.append("<Row>");

        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            xml.append("<").append(columnName).append(">");

            if (value != null) {
                xml.append(value.toString().trim());
            }
            xml.append("</").append(columnName).append(">");
        }
        xml.append("</Row>");
    }

    xml.append("</Results>");

    return xml.toString();
}

From source file:com.example.querybuilder.server.Jdbc.java

public static ResultSetMetaData getMetaData(ResultSet resultSet) {
    try {/*from  w  w w. j av  a  2  s.  c om*/
        return resultSet.getMetaData();
    } catch (SQLException e) {
        throw new SqlRuntimeException(e);
    }
}