Example usage for java.sql ResultSet findColumn

List of usage examples for java.sql ResultSet findColumn

Introduction

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

Prototype

int findColumn(String columnLabel) throws SQLException;

Source Link

Document

Maps the given ResultSet column label to its ResultSet column index.

Usage

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 a  v a 2  s . 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.abixen.platform.service.businessintelligence.multivisualization.service.impl.AbstractDatabaseService.java

private DataValueWeb getDataFromColumn(ResultSet row, String columnName) {
    try {/* w  w w  .j av a 2s. co m*/
        ResultSetMetaData resultSetMetaData = row.getMetaData();
        String columnTypeName = resultSetMetaData.getColumnTypeName(row.findColumn(columnName)).toUpperCase();
        if ("BIGINT".equals(columnTypeName)) {
            columnTypeName = "INTEGER";
        }
        if ("VARCHAR".equals(columnTypeName)) {
            columnTypeName = "STRING";
        }
        if ("FLOAT8".equals(columnTypeName)) {
            columnTypeName = "DOUBLE";
        }
        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.abixen.platform.service.businessintelligence.multivisualisation.service.impl.AbstractDatabaseService.java

private DataValueWeb getDataFromColumn(ResultSet row, String columnName) {
    try {//from  w w w.j av a 2s  .c om
        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.gzj.tulip.jade.rowmapper.MapEntryColumnRowMapper.java

public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

    // ?/*from w  ww .ja va 2  s.co m*/
    if (rowNum == 0) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int nrOfColumns = rsmd.getColumnCount();
        if (nrOfColumns != 2) {
            throw new IncorrectResultSetColumnCountException(2, nrOfColumns);
        }

        if (StringUtils.isNotEmpty(keyColumn)) {
            keyColumnIndex = rs.findColumn(keyColumn);
            if (keyColumnIndex == 1) {
                valueColumnIndex = 2;
            } else if (keyColumnIndex == 2) {
                valueColumnIndex = 1;
            } else {
                throw new IllegalArgumentException(
                        String.format("wrong key name %s for method: %s ", keyColumn, modifier.getMethod()));
            }
            keyColumn = null;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("keyIndex=%s; valueIndex=%s; for method: %s ", keyColumnIndex,
                    valueColumnIndex, modifier.getMethod()));
        }
    }

    //   JDBC ResultSet ?  Key
    Object key = JdbcUtils.getResultSetValue(rs, keyColumnIndex, keyType);
    if (key != null && !keyType.isInstance(key)) {
        ResultSetMetaData rsmd = rs.getMetaData();
        throw new TypeMismatchDataAccessException( // NL
                "Type mismatch affecting row number " + rowNum + " and column type '"
                        + rsmd.getColumnTypeName(keyColumnIndex) + "' expected type is '" + keyType + "'");
    }

    //   JDBC ResultSet ?  Value
    Object value = JdbcUtils.getResultSetValue(rs, valueColumnIndex, valueType);
    if (value != null && !valueType.isInstance(value)) {
        ResultSetMetaData rsmd = rs.getMetaData();
        throw new TypeMismatchDataAccessException( // NL
                "Type mismatch affecting row number " + rowNum + " and column type '"
                        + rsmd.getColumnTypeName(valueColumnIndex) + "' expected type is '" + valueType + "'");
    }

    // key?null??
    return new MapEntryImpl<Object, Object>(key, value);
}

From source file:edu.ku.brc.af.auth.specify.SpecifySecurityMgr.java

@Override
public boolean authenticateDB(final String user, final String pass, final String driverClass, final String url,
        final String dbUserName, final String dbPwd) throws Exception {
    Connection conn = null;// ww  w.  j  a  v  a  2s .  c  o m
    Statement stmt = null;
    boolean passwordMatch = false;

    try {
        Class.forName(driverClass);

        conn = DriverManager.getConnection(url, dbUserName, dbPwd);

        String query = "SELECT * FROM specifyuser where name='" + user + "'"; //$NON-NLS-1$ //$NON-NLS-2$
        stmt = conn.createStatement();
        ResultSet result = stmt.executeQuery(query);
        String dbPassword = null;

        while (result.next()) {
            if (!result.isFirst()) {
                throw new LoginException("authenticateDB - Ambiguous user (located more than once): " + user); //$NON-NLS-1$
            }
            dbPassword = result.getString(result.findColumn("Password")); //$NON-NLS-1$

            if (StringUtils.isNotEmpty(dbPassword) && StringUtils.isAlphanumeric(dbPassword)
                    && UIHelper.isAllCaps(dbPassword) && dbPassword.length() > 20) {
                dbPassword = Encryption.decrypt(dbPassword, pass);
            }
            break;
        }

        /*if (dbPassword == null)
        {
        throw new LoginException("authenticateDB - Password for User " + user + " undefined."); //$NON-NLS-1$ //$NON-NLS-2$
        }*/
        if (pass != null && dbPassword != null && pass.equals(dbPassword)) {
            passwordMatch = true;
        }

        // else: passwords do NOT match, user will not be authenticated
    } catch (java.lang.ClassNotFoundException e) {
        e.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifySecurityMgr.class, e);
        log.error("authenticateDB - Could not connect to database, driverclass - ClassNotFoundException: "); //$NON-NLS-1$
        log.error(e.getMessage());
        throw new LoginException("authenticateDB -  Database driver class not found: " + driverClass); //$NON-NLS-1$
    } catch (SQLException ex) {
        if (debug)
            log.error("authenticateDB - SQLException: " + ex.toString()); //$NON-NLS-1$
        if (debug)
            log.error("authenticateDB - " + ex.getMessage()); //$NON-NLS-1$
        throw new LoginException("authenticateDB - SQLException: " + ex.getMessage()); //$NON-NLS-1$
    } finally {
        try {
            if (conn != null)
                conn.close();
            if (stmt != null)
                stmt.close();
        } catch (SQLException e) {
            edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifySecurityMgr.class, e);
            log.error("Exception caught: " + e.toString()); //$NON-NLS-1$
            e.printStackTrace();
        }
    }
    return passwordMatch;
}

From source file:com.iver.utiles.connections.ConnectionDB.java

/**
 * Returns the names of the tables/*from w  w w .  j av  a  2 s . c  om*/
 * 
 * @param conn
 *            Connection
 * 
 * @return Array of string with the names of the tables.
 * 
 * @throws ConnectionException
 */
public String[] getTableNames(Connection conn) throws ConnectionException {
    // Connection conn=getConnectionByName(name);
    ArrayList tableNames = new ArrayList();
    String nombreTablas = "%"; // Listamos todas las tablas
    String[] tipos = new String[1]; // Listamos slo tablas
    tipos[0] = "TABLE";

    try {
        DatabaseMetaData dbmd = conn.getMetaData();
        ResultSet tablas = dbmd.getTables(null, null, nombreTablas, tipos);

        boolean seguir = tablas.next();

        while (seguir) {
            // Mostramos slo el nombre de las tablas, guardado
            // en la columna "TABLE_NAME"
            System.out.println(tablas.getString(tablas.findColumn("TABLE_NAME")));
            tableNames.add(tablas.getString(tablas.findColumn("TABLE_NAME")));
            seguir = tablas.next();
        }
    } catch (SQLException e) {
        throw new ConnectionException(JDBCManager.getTranslation("fallo_obtener_tablas"), e);
    }

    return (String[]) tableNames.toArray(new String[0]);
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

public void testFindColumn() throws SQLException {
    trace("testFindColumn");
    stat = conn.createStatement();/*from  w w w.j  a  va  2s .  com*/
    stat.executeUpdate(
            "Insert into " + TABLE_NAME + "(column1,column2,column3) values (3031,11,'binlijin3031');");
    ResultSet rs = stat.executeQuery(
            "SELECT column1,column2,column3 FROM test where column1=3031 and column3='binlijin3031'");
    // assertEquals(1, rs.findColumn("COLUMN1"));
    // assertEquals(2, rs.findColumn("COLUMN2"));
    assertEquals(1, rs.findColumn("column1"));
    assertEquals(2, rs.findColumn("column2"));
    // assertEquals(1, rs.findColumn("Column1"));
    // assertEquals(2, rs.findColumn("Column2"));
}

From source file:com.alkacon.opencms.formgenerator.database.CmsFormDataAccess.java

/**
 * Checks if the db tables for the webform data exist and is up-to-date.<p> 
 * //  w w w  .j  av a  2  s .  c  o  m
 * @return -1 if the db tables do not exist,
 *          0 if the db tables do exist, in the current version, or
 *          1 if the db tables do exist, in an old version
 * 
 * @throws SQLException if problems with the db connectivity occur
 */
private int existsDBTables() throws SQLException {

    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet res = null;
    try {
        con = getConnection();
        stmt = con.prepareStatement(getQuery("CHECK_TABLES"));
        try {
            res = stmt.executeQuery();
            try {
                res.findColumn(DB_RESOURCE_ID);
                return 0;
            } catch (Exception ex) {
                if (LOG.isInfoEnabled()) {
                    LOG.info(Messages.get().getBundle().key(Messages.LOG_INFO_DATAACESS_SQL_TABLE_OLD_0), ex);
                }
            }
            return 1;
        } catch (Exception ex) {
            if (LOG.isInfoEnabled()) {
                LOG.info(Messages.get().getBundle().key(Messages.LOG_INFO_DATAACESS_SQL_TABLE_NOTEXISTS_0), ex);
            }
        }
    } finally {
        closeAll(con, stmt, res);
    }
    return -1;
}

From source file:net.antidot.semantic.rdf.rdb2rdf.dm.core.DirectMappingEngineWD20120529.java

private Row extractRow(DriverType driver, StdHeader header, String tableName, ResultSet valueSet,
        String timeZone, int index) throws UnsupportedEncodingException {
    TreeMap<String, byte[]> values = new TreeMap<String, byte[]>();
    for (String columnName : header.getColumnNames()) {
        try {/*  w  w w.  j a  va2s. c  o m*/
            byte[] value = null;
            // SQLType type =
            // SQLType.toSQLType(Integer.valueOf(header.getDatatypes().get(columnName)));
            value = valueSet.getBytes(columnName);

            // http://bugs.mysql.com/bug.php?id=65943
            if (value != null && driver.equals(DriverType.MysqlDriver) && SQLType.toSQLType(
                    valueSet.getMetaData().getColumnType(valueSet.findColumn(columnName))) == SQLType.CHAR) {
                value = valueSet.getString(columnName).getBytes();
            }

            values.put(columnName, value);
        } catch (SQLException e) {
            log.error("[DirectMappingEngine:extractRow] SQL Error during row extraction");
            e.printStackTrace();
        }
    }
    Row row = new Row(values, null, index);
    return row;
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java

private void validateResultSetMetadata(List<ConfigIssue> issues, Source.Context context, ResultSet rs) {
    Set<String> allTables = new HashSet<>();
    try {/*from  ww w. jav  a 2s.c o  m*/
        Set<String> columnLabels = new HashSet<>();
        ResultSetMetaData metadata = rs.getMetaData();
        int columnIdx = metadata.getColumnCount() + 1;
        while (--columnIdx > 0) {
            String columnLabel = metadata.getColumnLabel(columnIdx);
            if (columnLabels.contains(columnLabel)) {
                issues.add(
                        context.createConfigIssue(Groups.JDBC.name(), QUERY, JdbcErrors.JDBC_31, columnLabel));
            } else {
                columnLabels.add(columnLabel);
            }
            allTables.add(metadata.getTableName(columnIdx));
        }
        if (!StringUtils.isEmpty(offsetColumn) && offsetColumn.contains(".")) {
            issues.add(context.createConfigIssue(Groups.JDBC.name(), OFFSET_COLUMN, JdbcErrors.JDBC_32,
                    offsetColumn));
        } else {
            rs.findColumn(offsetColumn);
        }
    } catch (SQLException e) {
        // Log a warning instead of an error because some implementations such as Oracle have implicit
        // "columns" such as ROWNUM that won't appear as part of the result set.
        LOG.warn(JdbcErrors.JDBC_33.getMessage(), offsetColumn, query);
        LOG.warn(jdbcUtil.formatSqlException(e));
    }
    tableNames = StringUtils.join(allTables, ", ");
}