Example usage for java.sql ResultSetMetaData getTableName

List of usage examples for java.sql ResultSetMetaData getTableName

Introduction

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

Prototype

String getTableName(int column) throws SQLException;

Source Link

Document

Gets the designated column's table name.

Usage

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

BaseDatatype findFieldDataType(String field, ResultSet rs) {
    field = field.trim();/*w w w.j ava 2  s  .  co  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:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java

/**
 * @param resultSet//from   w  ww . j  a  v  a2  s  .  co  m
 * @return
 */
private Map extractRowKey(ResultSet resultSet, String tableHint) throws SQLException {
    ResultSetMetaData rsMeta = resultSet.getMetaData();
    TableName tableName = new TableName(rsMeta.getCatalogName(1), rsMeta.getSchemaName(1),
            rsMeta.getTableName(1));
    String completeTableName = tableName.getCompleteName();
    if (completeTableName == null || completeTableName.trim().equals("")) {
        completeTableName = tableHint;
    }

    Map keys = new KeyMap();
    List keyColumns = (List) _tables.get(String.valueOf(completeTableName).toLowerCase());

    // If key columns are not retrievable, just return the empty map as key
    if (keyColumns == null) {
        return keys;
    }

    Iterator keyColumnsIt = keyColumns.iterator();
    while (keyColumnsIt.hasNext()) {
        String keyColumn = (String) keyColumnsIt.next();
        Object keyValue = resultSet.getObject(keyColumn);

        // Since the key columns from KeyMap originate from the _tables list, we should use the column names unmodified
        // keys.put(keyColumn.toLowerCase(), keyValue);
        keys.put(keyColumn, keyValue);
    }

    return keys;

}

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() + ".";
            }/* w  ww  .java 2  s. c  o 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;
}

From source file:com.commander4j.db.JDBUserReport.java

private boolean generateAccess(ResultSet temp) {
    boolean result = true;
    setExportFilename(getExportPath() + getReportID() + "_"
            + JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime()).replace("T", "_")
                    .replace("-", "_").replace(":", "_")
            + ".mdb");
    setExportFilename(promptUserforSave());

    try {//from   w w w.jav  a 2  s. co  m
        ResultSetMetaData rsmd = temp.getMetaData();
        String tablename = rsmd.getTableName(1);
        Database db = DatabaseBuilder.create(Database.FileFormat.V2007, new File(getExportFilename()));
        db = DatabaseBuilder.open(new File(getExportFilename()));
        new ImportUtil.Builder(db, tablename).importResultSet(temp);
        db.close();

    } catch (Exception e) {
        result = false;
        setErrorMessage(e.getMessage());
    }
    return result;
}

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

/**
 * @param sql//from   w w w . j a  v  a  2  s .c  o  m
 * @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:org.ensembl.healthcheck.util.DBUtils.java

/**
 * Compare a particular column in two ResultSets.
 * /*from   www  .j av  a  2 s. c om*/
 * @param rs1
 *            The first ResultSet to compare.
 * @param rs2
 *            The second ResultSet to compare.
 * @param i
 *            The index of the column to compare.
 * @return True if the type and value of the columns match.
 */
public static boolean compareColumns(ResultSet rs1, ResultSet rs2, int i, boolean warnNull) {

    try {

        ResultSetMetaData rsmd = rs1.getMetaData();

        Connection con1 = rs1.getStatement().getConnection();
        Connection con2 = rs2.getStatement().getConnection();

        if (rs1.getObject(i) == null) {
            if (warnNull) {
                logger.fine("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i)
                        + " in " + DBUtils.getShortDatabaseName(con1));
            }
            return (rs2.getObject(i) == null); // true if both are null
        }
        if (rs2.getObject(i) == null) {
            if (warnNull) {
                logger.fine("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i)
                        + " in " + DBUtils.getShortDatabaseName(con2));
            }
            return (rs1.getObject(i) == null); // true if both are null
        }

        // Note deliberate early returns for performance reasons
        switch (rsmd.getColumnType(i)) {

        case Types.INTEGER:
            return rs1.getInt(i) == rs2.getInt(i);

        case Types.SMALLINT:
            return rs1.getInt(i) == rs2.getInt(i);

        case Types.TINYINT:
            return rs1.getInt(i) == rs2.getInt(i);

        case Types.VARCHAR:
            String s1 = rs1.getString(i);
            String s2 = rs2.getString(i);
            // ignore "AUTO_INCREMENT=" part in final part of table
            // definition
            s1 = s1.replaceAll("AUTO_INCREMENT=[0-9]+ ", "");
            s2 = s2.replaceAll("AUTO_INCREMENT=[0-9]+ ", "");
            return s1.equals(s2);

        case Types.FLOAT:
            return rs1.getFloat(i) == rs2.getFloat(i);

        case Types.DOUBLE:
            return rs1.getDouble(i) == rs2.getDouble(i);

        case Types.TIMESTAMP:
            return rs1.getTimestamp(i).equals(rs2.getTimestamp(i));

        default:
            // treat everything else as a String (should deal with ENUM and
            // TEXT)
            if (rs1.getString(i) == null || rs2.getString(i) == null) {
                return true; // ????
            } else {
                return rs1.getString(i).equals(rs2.getString(i));
            }

        } // switch

    } catch (SQLException se) {
        throw new SqlUncheckedException("Could not compare two columns sets", se);
    }

}

From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ResultSetTableModelFactory.java

public static AttributeMap<Object> collectData(final ResultSetMetaData rsmd, final int column,
        final String name) throws SQLException {
    AttributeMap<Object> metaData = new AttributeMap<Object>();
    metaData.setAttribute(MetaAttributeNames.Core.NAMESPACE, MetaAttributeNames.Core.TYPE,
            TypeMapper.mapForColumn(rsmd, column));
    metaData.setAttribute(MetaAttributeNames.Core.NAMESPACE, MetaAttributeNames.Core.NAME, name);
    try {//from   w  ww  .j  a  v a 2 s. c  o m
        if (rsmd.isCurrency(column + 1)) {
            metaData.setAttribute(MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.CURRENCY,
                    Boolean.TRUE);
        } else {
            metaData.setAttribute(MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.CURRENCY,
                    Boolean.FALSE);
        }
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#isCurrency. Driver does not implement the JDBC specs correctly. ",
                e);
    }
    try {

        if (rsmd.isSigned(column + 1)) {
            metaData.setAttribute(MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.SIGNED,
                    Boolean.TRUE);
        } else {
            metaData.setAttribute(MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.SIGNED,
                    Boolean.FALSE);
        }
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#isSigned. Driver does not implement the JDBC specs correctly. ", e);
    }

    try {
        final String tableName = rsmd.getTableName(column + 1);
        if (tableName != null) {
            metaData.setAttribute(MetaAttributeNames.Database.NAMESPACE, MetaAttributeNames.Database.TABLE,
                    tableName);
        }
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#getTableName. Driver does not implement the JDBC specs correctly. ",
                e);
    }

    try {
        final String schemaName = rsmd.getSchemaName(column + 1);
        if (schemaName != null) {
            metaData.setAttribute(MetaAttributeNames.Database.NAMESPACE, MetaAttributeNames.Database.SCHEMA,
                    schemaName);
        }
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#getSchemaName. Driver does not implement the JDBC specs correctly. ",
                e);
    }

    try {
        final String catalogName = rsmd.getCatalogName(column + 1);
        if (catalogName != null) {
            metaData.setAttribute(MetaAttributeNames.Database.NAMESPACE, MetaAttributeNames.Database.CATALOG,
                    catalogName);
        }
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#getTableName. Driver does not implement the JDBC specs correctly. ",
                e);
    }

    try {
        final String label = rsmd.getColumnLabel(column + 1);
        if (label != null) {
            metaData.setAttribute(MetaAttributeNames.Formatting.NAMESPACE, MetaAttributeNames.Formatting.LABEL,
                    label);
        }
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#getTableName. Driver does not implement the JDBC specs correctly. ",
                e);
    }

    try {
        final int displaySize = rsmd.getColumnDisplaySize(column + 1);
        metaData.setAttribute(MetaAttributeNames.Formatting.NAMESPACE,
                MetaAttributeNames.Formatting.DISPLAY_SIZE, IntegerCache.getInteger(displaySize));
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#getTableName. Driver does not implement the JDBC specs correctly. ",
                e);
    }

    try {
        final int precision = rsmd.getPrecision(column + 1);
        metaData.setAttribute(MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.PRECISION,
                IntegerCache.getInteger(precision));
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#getTableName. Driver does not implement the JDBC specs correctly. ",
                e);
    }

    try {
        final int scale = rsmd.getScale(column + 1);
        metaData.setAttribute(MetaAttributeNames.Numeric.NAMESPACE, MetaAttributeNames.Numeric.SCALE,
                IntegerCache.getInteger(scale));
    } catch (SQLException e) {
        logger.debug(
                "Error on ResultSetMetaData#getTableName. Driver does not implement the JDBC specs correctly. ",
                e);
    }
    return metaData;
}

From source file:net.hydromatic.optiq.test.JdbcTest.java

/** Tests driver's implementation of {@link DatabaseMetaData#getColumns}. */
@Test/*from w  w w  .ja  va  2s.c o  m*/
public void testResultSetMetaData() throws ClassNotFoundException, SQLException {
    Connection connection = getConnection("hr", "foodmart");
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement
            .executeQuery("select \"empid\", \"deptno\" as x, 1 as y\n" + "from \"hr\".\"emps\"");
    ResultSetMetaData metaData = resultSet.getMetaData();
    assertEquals(3, metaData.getColumnCount());
    assertEquals("empid", metaData.getColumnLabel(1));
    assertEquals("empid", metaData.getColumnName(1));
    assertEquals("emps", metaData.getTableName(1));
    assertEquals("X", metaData.getColumnLabel(2));
    assertEquals("deptno", metaData.getColumnName(2));
    assertEquals("emps", metaData.getTableName(2));
    assertEquals("Y", metaData.getColumnLabel(3));
    assertEquals("Y", metaData.getColumnName(3));
    assertEquals(null, metaData.getTableName(3));
    resultSet.close();
    connection.close();
}

From source file:org.apache.kylin.rest.service.QueryService.java

/**
 * @param correctedSql/*from www. j a v  a 2  s. c  o  m*/
 * @param sqlRequest
 * @return
 * @throws Exception
 */
private SQLResponse execute(String correctedSql, SQLRequest sqlRequest) throws Exception {
    Connection conn = null;
    Statement stat = null;
    ResultSet resultSet = null;
    Boolean isPushDown = false;

    List<List<String>> results = Lists.newArrayList();
    List<SelectedColumnMeta> columnMetas = Lists.newArrayList();

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

        // special case for prepare query. 
        if (BackdoorToggles.getPrepareOnly()) {
            return getPrepareOnlySqlResponse(correctedSql, conn, isPushDown, results, columnMetas);
        }

        stat = conn.createStatement();
        processStatementAttr(stat, sqlRequest);
        resultSet = stat.executeQuery(correctedSql);

        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)));
        }

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

            results.add(oneRow);
        }
    } catch (SQLException sqlException) {
        isPushDown = PushDownUtil.doPushDownQuery(sqlRequest.getProject(), correctedSql, results, columnMetas,
                sqlException);
    } finally {
        close(resultSet, stat, conn);
    }

    return getSqlResponse(isPushDown, results, columnMetas);
}

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

/**
 * Use result set to initial a bean./*ww  w  . j  a  v  a  2 s  .  c  om*/
 * 
 * @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);
    }

}