Example usage for java.sql ResultSetMetaData getColumnTypeName

List of usage examples for java.sql ResultSetMetaData getColumnTypeName

Introduction

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

Prototype

String getColumnTypeName(int column) throws SQLException;

Source Link

Document

Retrieves the designated column's database-specific type name.

Usage

From source file:org.apache.kylin.query.KylinTestBase.java

protected int output(ResultSet resultSet, boolean needDisplay) throws SQLException {
    int count = 0;
    ResultSetMetaData metaData = resultSet.getMetaData();
    int columnCount = metaData.getColumnCount();
    StringBuilder sb = new StringBuilder("\n");
    if (needDisplay) {
        for (int i = 1; i <= columnCount; i++) {
            sb.append(metaData.getColumnName(i));
            sb.append("-");
            sb.append(metaData.getTableName(i));
            sb.append("-");
            sb.append(metaData.getColumnTypeName(i));
            if (i < columnCount) {
                sb.append("\t");
            } else {
                sb.append("\n");
            }/*from   w w  w  .  ja v a  2 s .  c o  m*/
        }
    }

    while (resultSet.next()) {
        if (needDisplay) {
            for (int i = 1; i <= columnCount; i++) {
                sb.append(resultSet.getString(i));
                if (i < columnCount) {
                    sb.append("\t");
                } else {
                    sb.append("\n");
                }
            }
        }
        count++;
    }
    logger.info(sb.toString());
    return count;
}

From source file:com.chiorichan.database.DatabaseEngine.java

public List<String> getTableFieldTypes(String table) throws SQLException {
    List<String> rtn = Lists.newArrayList();

    ResultSet rs = query("SELECT * FROM " + table);

    ResultSetMetaData rsmd = rs.getMetaData();

    int numColumns = rsmd.getColumnCount();

    for (int i = 1; i < numColumns + 1; i++) {
        rtn.add(rsmd.getColumnTypeName(i));
    }/*  ww w . jav a 2s .  c  o  m*/

    return rtn;
}

From source file:at.ac.tuwien.inso.subcat.reporter.Reporter.java

private void exportWordStats(final ExporterConfig config, Project project, int commitDictId, int bugDictId,
        Settings settings, final ReportWriter formatter, String outputPath, Map<String, Object> vars)
        throws SQLException, Exception {
    formatter.init(project, settings, outputPath);
    model.rawForeach(config.getQuery(), vars, new ResultCallback() {

        @Override//from w  ww  .  ja v  a  2  s  . c o m
        public void processResult(ResultSet res) throws SemanticException, SQLException, Exception {
            ResultSetMetaData meta = res.getMetaData();
            String[] titles = new String[meta.getColumnCount()];
            if (titles.length != 2) {
                throw new SemanticException(
                        "semantic error: invalid column count, expected: (<string>, <string>)",
                        config.getStart(), config.getEnd());
            }

            if (meta.getColumnType(1) != Types.VARCHAR || meta.getColumnType(2) != Types.VARCHAR) {
                throw new SemanticException(
                        "semantic error: invalid column type, expected: (<string>, <string>), got " + "(<"
                                + meta.getColumnTypeName(1) + ">, <" + meta.getColumnTypeName(2) + ">)",
                        config.getStart(), config.getEnd());
            }

            Map<String, Map<String, Integer>> data = new HashMap<String, Map<String, Integer>>();
            Lemmatizer lemmatiser = new Lemmatizer();

            Set<String> categoryNames = new HashSet<String>();

            while (res.next()) {
                String category = res.getString(1);
                categoryNames.add(category);

                List<String> lemma = lemmatiser.lemmatize(res.getString(2));

                for (String word : lemma) {
                    Map<String, Integer> counter = data.get(word);
                    if (counter == null) {
                        counter = new HashMap<String, Integer>();
                        data.put(word, counter);
                    }

                    Integer wordCount = counter.get(category);
                    if (wordCount == null) {
                        wordCount = 0;
                    }

                    counter.put(category, wordCount + 1);
                }
            }

            String[] header = new String[categoryNames.size() + 1];
            header[0] = "word";

            int i = 1;
            for (String catName : categoryNames) {
                header[i] = catName;
                i++;
            }

            formatter.writeHeader(header);

            for (Entry<String, Map<String, Integer>> entry : data.entrySet()) {
                Map<String, Integer> scores = entry.getValue();
                String[] row = new String[header.length];

                row[0] = entry.getKey();
                i = 1;
                for (String cat : categoryNames) {
                    Integer score = scores.get(cat);
                    if (score == null) {
                        score = 0;
                    }
                    row[i] = score.toString();
                    i++;

                }

                formatter.writeSet(row);
            }

            formatter.writeFooter(header);
        }
    });
}

From source file:kenh.xscript.database.beans.ResultSetBean.java

/**
 * Use result set to initial a bean./*  ww  w  . j ava  2 s  . com*/
 * 
 * @param rs
 * @param includeFieldName
 * @throws SQLException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public ResultSetBean(ResultSet rs, boolean includeFieldName)
        throws SQLException, IllegalAccessException, InstantiationException {
    include_field_name = includeFieldName;

    LazyDynaClass beanClass = new LazyDynaClass();

    ResultSetMetaData m = rs.getMetaData();
    for (int i = 1; i <= m.getColumnCount(); i++) {
        Column c = new Column();

        try {
            c.catalogName = m.getCatalogName(i);
        } catch (SQLException e) {
        }
        try {
            c.className = m.getColumnClassName(i);
        } catch (SQLException e) {
        }
        try {
            c.displaySize = m.getColumnDisplaySize(i);
        } catch (SQLException e) {
        }
        try {
            c.label = m.getColumnLabel(i);
        } catch (SQLException e) {
        }
        try {
            c.name = m.getColumnName(i);
        } catch (SQLException e) {
        }
        try {
            c.type = m.getColumnType(i);
        } catch (SQLException e) {
        }
        try {
            c.typeName = m.getColumnTypeName(i);
        } catch (SQLException e) {
        }
        try {
            c.precision = m.getPrecision(i);
        } catch (SQLException e) {
        }
        try {
            c.scale = m.getScale(i);
        } catch (SQLException e) {
        }
        try {
            c.schemaName = m.getSchemaName(i);
        } catch (SQLException e) {
        }
        try {
            c.tableName = m.getTableName(i);
        } catch (SQLException e) {
        }

        beanClass.add(m.getColumnLabel(i).toLowerCase());
        beanClass.add("" + i);

        cols.add(c);
    }

    DynaBean colBean = beanClass.newInstance();
    int i = 1;
    for (Column col : cols) {
        String field = col.getLabel().toLowerCase();
        colBean.set(field, col.getLabel());
        colBean.set("" + i, col.getLabel());
        i++;
    }

    if (include_field_name)
        rows.add(colBean);

    while (rs.next()) {
        DynaBean bean = beanClass.newInstance();
        i = 1;
        for (Column c : cols) {
            String field = c.getLabel().toLowerCase();
            Object obj = rs.getObject(field);
            bean.set(field, obj);
            bean.set("" + i, obj);
            i++;
        }
        rows.add(bean);
    }

}

From source file:org.batoo.jpa.core.impl.criteria.QueryImpl.java

private void prepareLabels(final ResultSetMetaData md) throws SQLException {
    this.labels = new String[md.getColumnCount()];

    for (int i = 0; i < this.labels.length; i++) {
        String label = md.getColumnName(i + 1) + " (" + md.getColumnTypeName(i + 1) + ")";
        label = StringUtils.abbreviate(label, QueryImpl.MAX_COL_LENGTH);

        this.labels[i] = label;
    }/*from  w  w  w. ja  v  a 2s  . c  om*/
}

From source file:com.dbmojo.QueryExecutor.java

/** Execute a query i.e. NOT AN UPDATE. This method handles both
  * raw SQL and prepared statements.//from   w  w w .  j av a2s .com
  */
private HashMap executeQuery(Connection conn, boolean prepared, String query, String[] values)
        throws Exception {

    HashMap qObj = new HashMap();
    ArrayList<ArrayList<String>> rowList = new ArrayList<ArrayList<String>>();
    ArrayList<String> colList = new ArrayList<String>();
    ArrayList<String> typeList = new ArrayList<String>();

    ResultSet rset = null;
    PreparedStatement pstmt = null;
    Statement stmt = null;
    String rMessage = "";

    try {
        if (prepared) {
            pstmt = conn.prepareStatement(query);
            setPreparedStatementValues(pstmt, values);
            rset = pstmt.executeQuery();
            if (DebugLog.enabled) {
                DebugLog.add(this, "Prepared statement has been executed");
            }
        } else {
            stmt = conn.createStatement();
            rset = stmt.executeQuery(query);
            if (DebugLog.enabled) {
                DebugLog.add(this, "Statement has been executed");
            }
        }

        final ResultSetMetaData rsetMetaData = rset.getMetaData();
        final int numCols = rsetMetaData.getColumnCount();
        boolean firstRow = true;

        //Loop through all the result ROWs
        while (rset.next()) {
            ArrayList<String> valList = new ArrayList<String>();
            //JSONArray valArray = new JSONArray();
            //Loop through all the result COLs
            for (int i = 1; i <= numCols; i++) {
                if (firstRow) {
                    colList.add(rsetMetaData.getColumnName(i));
                    typeList.add(rsetMetaData.getColumnTypeName(i));
                }
                valList.add(rset.getString(i));
            }
            //Add each result row to a list of rows
            rowList.add(valList);
            firstRow = false;
        }

        if (DebugLog.enabled) {
            DebugLog.add(this, "Result set JSON created");
        }
    } catch (Exception e) {
        //If something goes wrong then return the error as the message for the
        //result. Do not return any rows or column headers
        final String err = "Couldn't Execute Query: " + e.toString();

        if (DebugLog.enabled) {
            DebugLog.add(this, err);
        }

        return Util.getError(err);
    } finally {
        //Cleanup up JDBC stuff
        if (rset != null) {
            rset.close();
            if (DebugLog.enabled) {
                DebugLog.add(this, "Closing result set");
            }
        }
        if (pstmt != null) {
            pstmt.close();
            if (DebugLog.enabled) {
                DebugLog.add(this, "Closing prepared statement");
            }
        }

        if (stmt != null) {
            stmt.close();
            if (DebugLog.enabled) {
                DebugLog.add(this, "Closing statement");
            }
        }
    }

    //Final JSON for this query is a JSON object
    //The rows attribute can be in either document or standard format
    qObj.put("types", typeList);
    qObj.put("cols", colList);
    qObj.put("rows", rowList);
    //No message necessary since everything went off without a hitch
    qObj.put("message", "");
    //If we get this far then we know things are good
    qObj.put("status", "success");

    return qObj;
}

From source file:org.openadaptor.auxil.connector.jdbc.writer.AbstractSQLWriter.java

/**
 * Determine the types of the columns in a table.
 * <br>/*from w w  w  . ja  v  a  2  s  .c  o  m*/
 * It does not check that the table exists, or that the columns actually
 * exist in the table.
 * @param tableName
 * @param connection
 * @param columnNames
 * @return int[] of database types.
 * @throws SQLException
 */
protected int[] getPreparedStatementTypes(String tableName, Connection connection, String[] columnNames)
        throws SQLException {
    //Execute a dummy sql statement against database purely to collect table metadata
    String sql = "SELECT * FROM " + tableName + " WHERE 1=2";
    Statement s = connection.createStatement();
    log.debug("Executing SQL: " + sql);
    ResultSet rs = s.executeQuery(sql);
    int[] types;
    ResultSetMetaData rsmd = rs.getMetaData();
    int cols = rsmd.getColumnCount();
    types = new int[columnNames.length];
    List nameList = Arrays.asList(columnNames);
    int mapped = 0;
    for (int i = 0; i < cols; i++) {
        int type = rsmd.getColumnType(i + 1);
        String name = rsmd.getColumnName(i + 1);
        int location = nameList.indexOf(name);
        if (location >= 0) {
            types[location] = type;
            mapped++;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Ignoring column " + i + "[" + name + " (" + rsmd.getColumnTypeName(i + 1) + ")]");
            }
        }
    }
    if (mapped < types.length) {
        log.warn("Not all column names were mapped. This is probably a configuration error");
    }
    return types;
}

From source file:at.ac.univie.isc.asio.engine.sql.WebRowSetWriter.java

private void columnDefinition(final int idx, final ResultSetMetaData context)
        throws XMLStreamException, SQLException {
    // @formatter:off
    xml.writeStartElement(WRS, "column-definition");
    tag("column-index", idx);
    tag("auto-increment", context.isAutoIncrement(idx));
    tag("case-sensitive", context.isCaseSensitive(idx));
    tag("currency", context.isCurrency(idx));
    tag("nullable", context.isNullable(idx));
    tag("signed", context.isSigned(idx));
    tag("searchable", context.isSearchable(idx));
    tag("column-display-size", context.getColumnDisplaySize(idx));
    tag("column-label", context.getColumnLabel(idx));
    tag("column-name", context.getColumnName(idx));
    tag("schema-name", context.getSchemaName(idx));
    tag("column-precision", context.getPrecision(idx));
    tag("column-scale", context.getScale(idx));
    tag("table-name", context.getTableName(idx));
    tag("catalog-name", context.getCatalogName(idx));
    tag("column-type", context.getColumnType(idx));
    tag("column-type-name", context.getColumnTypeName(idx));
    xml.writeEndElement();// w w  w .  ja v  a  2 s . co  m
    // @formatter:on
}

From source file:com.kylinolap.rest.service.QueryService.java

/**
 * @param sql//from  w w  w .  ja va2 s. com
 * @param project
 * @return
 * @throws Exception
 */
private SQLResponse execute(String sql, SQLRequest sqlRequest) throws Exception {
    Connection conn = null;
    Statement stat = null;
    ResultSet resultSet = null;
    List<List<String>> results = new LinkedList<List<String>>();
    List<SelectedColumnMeta> columnMetas = new LinkedList<SelectedColumnMeta>();

    try {
        conn = getOLAPDataSource(sqlRequest.getProject()).getConnection();

        if (sqlRequest instanceof PrepareSqlRequest) {
            PreparedStatement preparedState = conn.prepareStatement(sql);

            for (int i = 0; i < ((PrepareSqlRequest) sqlRequest).getParams().length; i++) {
                setParam(preparedState, i + 1, ((PrepareSqlRequest) sqlRequest).getParams()[i]);
            }

            resultSet = preparedState.executeQuery();
        } else {
            stat = conn.createStatement();
            resultSet = stat.executeQuery(sql);
        }

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        // Fill in selected column meta
        for (int i = 1; i <= columnCount; ++i) {
            columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i),
                    metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i),
                    metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i),
                    metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i),
                    metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i),
                    metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i),
                    metaData.isWritable(i), metaData.isDefinitelyWritable(i)));
        }

        List<String> oneRow = new LinkedList<String>();

        // fill in results
        while (resultSet.next()) {
            for (int i = 0; i < columnCount; i++) {
                oneRow.add((resultSet.getString(i + 1)));
            }

            results.add(new LinkedList<String>(oneRow));
            oneRow.clear();
        }
    } catch (Exception e) {
        logger.error(e.getLocalizedMessage(), e);
        throw e;
    } finally {
        close(resultSet, stat, conn);
    }

    boolean isPartialResult = false;
    String cube = "";
    long totalScanCount = 0;
    for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) {
        isPartialResult |= ctx.storageContext.isPartialResultReturned();
        cube = ctx.cubeInstance.getName();
        totalScanCount += ctx.storageContext.getTotalScanCount();
    }

    SQLResponse response = new SQLResponse(columnMetas, results, cube, 0, false, null, isPartialResult);
    response.setTotalScanCount(totalScanCount);

    return response;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public List<ColumnVO> getColumnsMetaData(String sql) throws Exception {
    Exception error = null;//  ww  w  . j ava  2s  . c  om

    List<ColumnVO> tableColumns = new LinkedList<ColumnVO>();

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        ResultSet rs = preparedStmnt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String columnName = rsmd.getColumnName(i);
            String columnType = rsmd.getColumnTypeName(i);
            int columnSqlType = rsmd.getColumnType(i);
            int columnLength = rsmd.getColumnDisplaySize(i);
            int columnPrecision = rsmd.getPrecision(i);

            ColumnVO column = new ColumnVO();
            column.setNameOnTable(columnName);
            column.setType(columnType);
            column.setSqlType(columnSqlType);
            column.setLength(columnLength);
            column.setPrecision(columnPrecision);
            column.setInTable(true);

            tableColumns.add(column);
        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }
    if (error != null) {
        throw error;
    }
    return tableColumns;
}