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.mvdb.etl.dao.impl.JdbcGenericDAO.java

@Override
public void fetchMetadata(String objectName, File snapshotDirectory) {
    final Metadata metadata = new Metadata();
    metadata.setTableName(objectName);//from  ww  w  .j  a v  a2  s .  c  o  m
    String sql = "SELECT * FROM " + objectName + " limit 1";
    final Map<String, ColumnMetadata> metaDataMap = new HashMap<String, ColumnMetadata>();
    metadata.setColumnMetadataMap(metaDataMap);
    metadata.setTableName(objectName);

    getJdbcTemplate().query(sql, new RowCallbackHandler() {

        @Override
        public void processRow(ResultSet row) throws SQLException {
            ResultSetMetaData rsm = row.getMetaData();
            int columnCount = rsm.getColumnCount();
            for (int column = 1; column < (columnCount + 1); column++) {
                ColumnMetadata columnMetadata = new ColumnMetadata();
                columnMetadata.setColumnLabel(rsm.getColumnLabel(column));
                columnMetadata.setColumnName(rsm.getColumnName(column));
                columnMetadata.setColumnType(rsm.getColumnType(column));
                columnMetadata.setColumnTypeName(rsm.getColumnTypeName(column));

                metaDataMap.put(rsm.getColumnName(column), columnMetadata);
            }

        }
    });

    writeMetadata(metadata, snapshotDirectory);
}

From source file:net.certifi.audittablegen.PostgresqlDMR.java

/**
 * Get List of ColumnDef objects for all tables
 * in the targeted database/schema.  Postgres specific code replaces 
 * 'serial' date type with integer, because the column in the audit table
 * must be of type integer and not serial.  Since this data is interpreted
 * by ChangeSourceFactory, which should be database independent, the
 * translation needs to be in the DMR./*w w w  .  j a  v  a2  s.  c  o m*/
 * 
 * @param tableName
 * @return ArrayList of ColumnDef objects or an empty list if none are found.
 */
@Override
public List getColumns(String tableName) {

    //getDataTypes will initialize the map if it isn't already loaded
    Map<String, DataTypeDef> dtds = getDataTypes();

    List columns = new ArrayList<>();

    try {
        Connection conn = dataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getColumns(null, verifiedSchema, tableName, null);

        //load all of the metadata in the result set into a map for each column

        ResultSetMetaData rsmd = rs.getMetaData();
        int metaDataColumnCount = rsmd.getColumnCount();
        if (!rs.isBeforeFirst()) {
            throw new RuntimeException(
                    "No results for DatabaseMetaData.getColumns(" + verifiedSchema + "." + tableName + ")");
        }
        while (rs.next()) {
            ColumnDef columnDef = new ColumnDef();
            Map columnMetaData = new CaseInsensitiveMap();
            for (int i = 1; i <= metaDataColumnCount; i++) {
                columnMetaData.put(rsmd.getColumnName(i), rs.getString(i));
            }
            columnDef.setName(rs.getString("COLUMN_NAME"));

            String type_name = rs.getString("TYPE_NAME");
            if (type_name.equalsIgnoreCase("serial")) {
                columnDef.setTypeName("int4");
            } else {
                columnDef.setTypeName(type_name);
            }
            columnDef.setSqlType(rs.getInt("DATA_TYPE"));
            columnDef.setSize(rs.getInt("COLUMN_SIZE"));
            columnDef.setDecimalSize(rs.getInt("DECIMAL_DIGITS"));
            columnDef.setSourceMeta(columnMetaData);

            if (dtds.containsKey(columnDef.getTypeName())) {
                columnDef.setDataTypeDef(dtds.get(columnDef.getTypeName()));
            } else {
                throw new RuntimeException(
                        "Missing DATA_TYPE definition for data type " + columnDef.getTypeName());
            }
            columns.add(columnDef);
        }

    } catch (SQLException e) {
        throw Throwables.propagate(e);
    }

    return columns;

}

From source file:ca.fastenalcompany.servlet.ProductServlet.java

public JSONArray query(String query, String... params) {
    Connection conn = null;//from ww  w. j a  v a2s.com
    JSONArray products = new JSONArray();
    try {
        conn = DBManager.getMysqlConn();
        PreparedStatement pstmt = conn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }
        System.out.println(query);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            JSONObject product = new JSONObject();
            for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) {
                String textLabel = rs.getMetaData().getColumnLabel(i);
                String textValue = rs.getString(textLabel);
                product.put(textLabel, textValue);
            }
            products.add(product);
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        try {
            System.out.println("DB connection closed");
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    return products;
}

From source file:com.netspective.axiom.sql.ResultSetUtils.java

/**
 * Create a text array that contains the headings of the columns in the given result set.
 *
 * @param resultSet                  The result set that we want to create column headers for
 * @param preferColumnLabelForHeader True if we want to use the label (if available) for a column or use it's name if unavailable or false
 *
 * @return The headings/*from   w ww.j a va 2s.  c o m*/
 */
public String[] getColumnHeadings(ResultSet resultSet, boolean preferColumnLabelForHeader) throws SQLException {
    ResultSetMetaData rsmd = resultSet.getMetaData();
    int columnsCount = rsmd.getColumnCount();

    String[] header = new String[columnsCount];
    if (preferColumnLabelForHeader) {
        for (int i = 1; i < columnsCount; i++) {
            String label = rsmd.getColumnLabel(i);
            if (label != null && label.length() > 0)
                header[i - 1] = label;
            else
                header[i - 1] = rsmd.getColumnName(i);
        }
    } else {
        for (int i = 1; i < columnsCount; i++)
            header[i - 1] = rsmd.getColumnName(i);
    }

    return header;
}

From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson5b.java

protected AttackResult injectableQuery(String accountName) {
    try {/*from   ww  w  . ja  va 2 s.c om*/
        Connection connection = DatabaseUtilities.getConnection(getWebSession());
        String query = "SELECT * FROM user_data WHERE userid = " + accountName;

        try {
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            ResultSet results = statement.executeQuery(query);

            if ((results != null) && (results.first() == true)) {
                ResultSetMetaData resultsMetaData = results.getMetaData();
                StringBuffer output = new StringBuffer();

                output.append(writeTable(results, resultsMetaData));
                results.last();

                // If they get back more than one user they succeeded
                if (results.getRow() >= 6) {
                    return trackProgress(AttackResult.success("You have succeed: " + output.toString()));
                } else {
                    return trackProgress(AttackResult.failed("You are close, try again. " + output.toString()));
                }

            } else {
                return trackProgress(AttackResult.failed("No Results Matched. Try Again. "));

                //                    output.append(getLabelManager().get("NoResultsMatched"));
            }
        } catch (SQLException sqle) {

            return trackProgress(AttackResult.failed(sqle.getMessage()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return trackProgress(
                AttackResult.failed("ErrorGenerating" + this.getClass().getName() + " : " + e.getMessage()));
    }
}

From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson6a.java

protected AttackResult injectableQuery(String accountName) {
    try {/*w  w  w. j  av a  2 s  .  c  o m*/
        Connection connection = DatabaseUtilities.getConnection(getWebSession());
        String query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'";

        try {
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            ResultSet results = statement.executeQuery(query);

            if ((results != null) && (results.first() == true)) {
                ResultSetMetaData resultsMetaData = results.getMetaData();
                StringBuffer output = new StringBuffer();

                output.append(writeTable(results, resultsMetaData));
                results.last();

                // If they get back more than one user they succeeded
                if (results.getRow() >= 6) {
                    return trackProgress(AttackResult.success("You have succeed: " + output.toString()));
                } else {
                    return trackProgress(AttackResult.failed("You are close, try again. " + output.toString()));
                }

            } else {
                return trackProgress(AttackResult.failed("No Results Matched. Try Again. "));

            }
        } catch (SQLException sqle) {

            return trackProgress(AttackResult.failed(sqle.getMessage()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return trackProgress(
                AttackResult.failed("ErrorGenerating" + this.getClass().getName() + " : " + e.getMessage()));
    }
}

From source file:com.abixen.platform.service.businessintelligence.multivisualisation.application.service.database.AbstractDatabaseService.java

private DataValueDto getDataFromColumn(ResultSet row, String columnName) {
    try {//from   ww w  .j av  a  2s . c  o  m
        ResultSetMetaData resultSetMetaData = row.getMetaData();
        String columnTypeName = getValidColumnTypeName(row.findColumn(columnName), resultSetMetaData);
        return getValueAsDataSourceValue(row, columnName, DataValueType.valueOf(columnTypeName));
    } catch (SQLException e) {
        throw new DataSourceValueException("Error when getting value from column. " + e.getMessage());
    }
}

From source file:com.serphacker.serposcope.db.base.ExportDB.java

public boolean export(Writer writer) throws IOException {
    for (String resource : MigrationDB.DB_SCHEMA_FILES) {
        String sql = new String(ByteStreams.toByteArray(MigrationDB.class.getResourceAsStream(resource)));
        sql = sql.replaceAll("--.*\n", "\n");
        sql = sql.replaceAll("\\s+", " ");
        sql = sql.replaceAll(";\\s*", ";\n");
        writer.append(sql);// ww w. j  a  v a2s.co  m
        writer.append("\n");
    }

    writer.append("\nSET FOREIGN_KEY_CHECKS=0;\n");
    try (Connection con = ds.getConnection()) {
        for (String table : TABLES) {
            writer.flush();
            try (Statement stmt = con.createStatement()) {
                LOG.info("exporting table {}", table);
                long _start = System.currentTimeMillis();

                stmt.setQueryTimeout(3600 * 24);
                ResultSet rs = stmt.executeQuery("SELECT * FROM `" + table + "`");
                ResultSetMetaData metaData = rs.getMetaData();
                int columns = metaData.getColumnCount();

                String insertStatement = "INSERT INTO `" + table + "` VALUES ";

                StringBuilder stmtBuilder = new StringBuilder(insertStatement);
                while (rs.next()) {

                    StringBuilder entryBuilder = new StringBuilder("(");
                    for (int colIndex = 1; colIndex <= columns; colIndex++) {
                        Object object = rs.getObject(colIndex);
                        String colName = metaData.getColumnName(colIndex);
                        String colClassName = metaData.getColumnClassName(colIndex);
                        String escaped = escape(object, colClassName, colName);
                        entryBuilder.append(escaped);
                        if (colIndex < columns) {
                            entryBuilder.append(',');
                        }
                    }
                    entryBuilder.append("),");

                    if (stmtBuilder.length() != insertStatement.length()
                            && stmtBuilder.length() + entryBuilder.length() > DEFAULT_MAX_ALLOWED_PACKET) {
                        stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                        writer.append(stmtBuilder).append('\n');
                        stmtBuilder = new StringBuilder(insertStatement);
                    }

                    stmtBuilder.append(entryBuilder);
                }

                if (stmtBuilder.length() != insertStatement.length()) {
                    stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                    writer.append(stmtBuilder).append('\n');
                }

                LOG.info("exported table {} in {}", table,
                        DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
            }
        }
        writer.append("SET FOREIGN_KEY_CHECKS=1;\n");
    } catch (Exception ex) {
        LOG.error("SQL error", ex);
        return false;
    }

    return true;
}

From source file:flex.messaging.io.ASRecordSet.java

public void populate(ResultSet rs) throws IOException {

    try {/*w ww . j a  va  2 s.com*/
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        String[] columnNames = new String[columnCount];

        int rowIndex = 0;
        List<List<Object>> initialData = new ArrayList<List<Object>>();
        while (rs.next()) {
            rowIndex++;
            List<Object> row = new ArrayList<Object>();
            for (int column = 0; column < columnCount; column++) {
                if (rowIndex == 1) {
                    columnNames[column] = rsmd.getColumnName(column + 1);
                }
                row.add(rs.getObject(column + 1));
            }
            if (rowIndex == 1) {
                setColumnNames(columnNames);
            }
            rows.add(row);
            if (rowIndex <= initialRowCount) {
                initialData.add(row);
            }
        }
        setTotalCount(rowIndex);
        setInitialData(initialData);
        setColumnNames(columnNames);
    } catch (SQLException e) {
        throw new IOException(e.getMessage());
    }

}

From source file:kr.co.bitnine.octopus.engine.CursorHive.java

@Override
public TupleDesc describe() throws PostgresException {
    if (tupDesc != null)
        return tupDesc;

    prepareConnection();/*w  ww  .ja  v a 2s.c o m*/
    prepareStatement(0);
    try {
        checkCancel();
        ResultSet rs = stmt.executeQuery();
        checkCancel();
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCnt = rsmd.getColumnCount();
        PostgresAttribute[] attrs = new PostgresAttribute[colCnt];
        for (int i = 0; i < colCnt; i++) {
            String colName = getColumnName(rsmd.getColumnName(i + 1));
            int colType = rsmd.getColumnType(i + 1);
            LOG.debug("JDBC type of column '" + colName + "' is " + colType);
            PostgresType type = TypeInfo.postresTypeOfJdbcType(colType);
            int typeInfo = -1;
            if (type == PostgresType.VARCHAR)
                typeInfo = rsmd.getColumnDisplaySize(i + 1);
            attrs[i] = new PostgresAttribute(colName, type, typeInfo);
        }
        rs.close();
        stmt.close();
        stmt = null;

        tupDesc = new TupleDesc(attrs, getResultFormats());
        return tupDesc;
    } catch (SQLException e) {
        PostgresErrorData edata = new PostgresErrorData(PostgresSeverity.ERROR,
                "failed to execute by-pass query: " + e.getMessage());
        throw new PostgresException(edata, e);
    }
}