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.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testInt() throws SQLException {
    trace("test INT");
    ResultSet rs;
    Object o;//  w w w .  j  ava  2 s .c  o  m
    stat = conn.createStatement();
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(31,-1, 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(32,0, 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(33,1, 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(34," + Integer.MAX_VALUE + ", 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(35," + Integer.MIN_VALUE + ", 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(36,0, 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(37,0, 'testInt')");
    // this should not be read - maxrows=6

    // MySQL compatibility (is this required?)
    rs = stat.executeQuery("SELECT column1,column2,column3 FROM test where column3='testInt' ORDER BY column1");
    // MySQL compatibility
    assertEquals(1, rs.findColumn("column1"));
    assertEquals(2, rs.findColumn("column2"));

    ResultSetMetaData meta = rs.getMetaData();
    assertEquals(3, meta.getColumnCount());

    assertTrue(rs.getRow() == 0);

    rs.next();
    trace("default fetch size=" + rs.getFetchSize());
    // 0 should be an allowed value (but it's not defined what is actually
    // means)
    rs.setFetchSize(1);
    assertThrows(SQLErrorCode.INVALID_VALUE_2, rs).setFetchSize(-1);
    // fetch size 100 is bigger than maxrows - not allowed
    rs.setFetchSize(6);

    assertTrue(rs.getRow() == 1);
    assertEquals(2, rs.findColumn("COLUMN2"));
    assertEquals(2, rs.findColumn("column2"));
    assertEquals(2, rs.findColumn("Column2"));
    assertEquals(1, rs.findColumn("COLUMN1"));
    assertEquals(1, rs.findColumn("column1"));
    assertEquals(1, rs.findColumn("Column1"));
    assertEquals(1, rs.findColumn("colUMN1"));
    assertTrue(rs.getInt(2) == -1 && !rs.wasNull());
    assertTrue(rs.getInt("COLUMN2") == -1 && !rs.wasNull());
    assertTrue(rs.getInt("column2") == -1 && !rs.wasNull());
    assertTrue(rs.getInt("Column2") == -1 && !rs.wasNull());
    assertTrue(rs.getString("Column2").equals("-1") && !rs.wasNull());

    o = rs.getObject("column2");
    trace(o.getClass().getName());
    assertTrue(o instanceof Long);
    assertTrue(((Long) o).longValue() == -1);
    o = rs.getObject(2);
    trace(o.getClass().getName());
    assertTrue(o instanceof Long);
    assertTrue(((Long) o).longValue() == -1);
    assertTrue(rs.getBoolean("Column2"));
    assertTrue(rs.getByte("Column2") == (byte) -1);
    assertTrue(rs.getShort("Column2") == (short) -1);
    assertTrue(rs.getLong("Column2") == -1);
    assertTrue(rs.getFloat("Column2") == -1.0);
    assertTrue(rs.getDouble("Column2") == -1.0);

    assertTrue(rs.getString("Column2").equals("-1") && !rs.wasNull());
    assertTrue(rs.getInt("COLUMN1") == 31 && !rs.wasNull());
    assertTrue(rs.getInt("column1") == 31 && !rs.wasNull());
    assertTrue(rs.getInt("Column1") == 31 && !rs.wasNull());
    assertTrue(rs.getInt(1) == 31 && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 2);
    assertTrue(rs.getInt(2) == 0 && !rs.wasNull());
    assertTrue(!rs.getBoolean(2));
    assertTrue(rs.getByte(2) == 0);
    assertTrue(rs.getShort(2) == 0);
    assertTrue(rs.getLong(2) == 0);
    assertTrue(rs.getFloat(2) == 0.0);
    assertTrue(rs.getDouble(2) == 0.0);
    assertTrue(rs.getString(2).equals("0") && !rs.wasNull());
    assertTrue(rs.getInt(1) == 32 && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 3);
    assertTrue(rs.getInt("COLUMN1") == 33 && !rs.wasNull());
    assertTrue(rs.getInt("COLUMN2") == 1 && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 4);
    assertTrue(rs.getInt("COLUMN1") == 34 && !rs.wasNull());
    assertTrue(rs.getInt("COLUMN2") == Integer.MAX_VALUE && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 5);
    assertTrue(rs.getInt("column1") == 35 && !rs.wasNull());
    assertTrue(rs.getInt("column2") == Integer.MIN_VALUE && !rs.wasNull());
    assertTrue(rs.getString(1).equals("35") && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 6);
    assertTrue(rs.getInt("column1") == 36 && !rs.wasNull());
    assertTrue(rs.getInt("column2") == 0 && !rs.wasNull());
    assertTrue(rs.getInt(2) == 0 && !rs.wasNull());
    assertTrue(rs.getInt(1) == 36 && !rs.wasNull());
    assertTrue(rs.getString(1).equals("36") && !rs.wasNull());
    assertTrue(rs.getString(2).equals("0") && !rs.wasNull());
    assertTrue(!rs.wasNull());
    // assertFalse(rs.next());
    // assertEquals(0, rs.getRow());
    // there is one more row, but because of setMaxRows we don't get it
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

@Test
public void testExecuteSQLQuery() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);
    assertSame(statement, rs.getStatement());

    assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType());
    assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency());
    assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability());

    assertFalse(rs.isClosed());/* w w w  . j a v a  2 s . c  om*/
    assertTrue(rs.isBeforeFirst());
    assertFalse(rs.isAfterLast());

    assertEquals(1, rs.findColumn("empno"));
    assertEquals(2, rs.findColumn("ename"));
    assertEquals(3, rs.findColumn("salary"));
    assertEquals(4, rs.findColumn("hiredate"));

    int count = printResultSet(rs);

    assertEquals(getEmpRowCount(), count);
    assertFalse(rs.isBeforeFirst());
    assertTrue(rs.isAfterLast());
    rs.close();
    assertTrue(rs.isClosed());

    statement.close();
    assertTrue(statement.isClosed());
}

From source file:org.mayocat.shop.billing.store.jdbi.mapper.OrderMapper.java

@Override
public Order map(int index, ResultSet resultSet, StatementContext ctx) throws SQLException {
    Order order = new Order();
    fillOrderSummary(resultSet, order);//  w ww.  ja v  a2  s. co  m

    ObjectMapper mapper = new ObjectMapper();
    //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        List<Map<String, Object>> itemsData = mapper.readValue(resultSet.getString("items"),
                new TypeReference<List<Map<String, Object>>>() {
                });

        List<OrderItem> items = FluentIterable.from(itemsData)
                .transform(new Function<Map<String, Object>, OrderItem>() {
                    public OrderItem apply(Map<String, Object> map) {
                        OrderItem orderItem = new OrderItem();
                        orderItem.setId(UUID.fromString((String) map.get("id")));
                        orderItem.setOrderId(UUID.fromString((String) map.get("order_id")));
                        if (map.containsKey("purchasable_id") && map.get("purchasable_id") != null) {
                            // There might not be a purchasable id
                            orderItem.setPurchasableId(UUID.fromString((String) map.get("purchasable_id")));
                        }
                        orderItem.setType((String) map.get("type"));
                        orderItem.setTitle((String) map.get("title"));
                        orderItem.setMerchant((String) map.get("merchant"));
                        orderItem.setQuantity(((Integer) map.get("quantity")).longValue());
                        orderItem.setUnitPrice(BigDecimal.valueOf((Double) map.get("unit_price")));
                        orderItem.setItemTotal(BigDecimal.valueOf((Double) map.get("item_total")));
                        if (map.containsKey("vat_rate") && map.get("vat_rate") != null) {
                            // There might not be a VAT rate
                            orderItem.setVatRate(BigDecimal.valueOf((Double) map.get("vat_rate")));
                        }
                        if (map.containsKey("data") && map.get("data") != null) {
                            // There might not be data
                            orderItem.addData((Map<String, Object>) map.get("data"));
                        }
                        return orderItem;
                    }
                }).toList();
        order.setOrderItems(items);
    } catch (IOException e) {
        logger.error("Failed to deserialize order data", e);
    }

    try {
        resultSet.findColumn("email");
        Customer customer = new Customer();
        customer.setId(order.getCustomerId());
        customer.setSlug(resultSet.getString("customer_slug"));
        customer.setEmail(resultSet.getString("email"));
        customer.setFirstName(resultSet.getString("first_name"));
        customer.setLastName(resultSet.getString("last_name"));
        customer.setPhoneNumber(resultSet.getString("phone_number"));
        order.setCustomer(customer);
    } catch (SQLException e) {
        // Nevermind
    }

    try {
        if (resultSet.getObject("billing_address_id") != null) {
            resultSet.findColumn("billing_address_full_name");
            Address billing = new Address();
            billing.setId((UUID) resultSet.getObject("billing_address_id"));
            billing.setFullName(resultSet.getString("billing_address_full_name"));
            billing.setStreet(resultSet.getString("billing_address_street"));
            billing.setStreetComplement(resultSet.getString("billing_address_street_complement"));
            billing.setZip(resultSet.getString("billing_address_zip"));
            billing.setCity(resultSet.getString("billing_address_city"));
            billing.setCountry(resultSet.getString("billing_address_country"));
            billing.setNote(resultSet.getString("billing_address_note"));
            order.setBillingAddress(billing);
        }
    } catch (SQLException e) {
        // Nevermind
    }

    try {
        if (resultSet.getObject("delivery_address_id") != null) {
            resultSet.findColumn("delivery_address_full_name");
            Address delivery = new Address();
            delivery.setId((UUID) resultSet.getObject("delivery_address_id"));
            delivery.setFullName(resultSet.getString("delivery_address_full_name"));
            delivery.setStreet(resultSet.getString("delivery_address_street"));
            delivery.setStreetComplement(resultSet.getString("delivery_address_street_complement"));
            delivery.setZip(resultSet.getString("delivery_address_zip"));
            delivery.setCity(resultSet.getString("delivery_address_city"));
            delivery.setCountry(resultSet.getString("delivery_address_country"));
            delivery.setNote(resultSet.getString("delivery_address_note"));
            order.setDeliveryAddress(delivery);
        }
    } catch (SQLException e) {
        // Nevermind
    }

    return order;
}

From source file:io.vitess.jdbc.VitessMySQLDatabaseMetadata.java

@SuppressWarnings("StringBufferReplaceableByString")
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)
        throws SQLException {
    ResultSet resultSet = null;
    VitessStatement vitessStatement = null;
    boolean reportTables = false;
    boolean reportViews = false;
    boolean reportSystemTables = false;
    boolean reportSystemViews = false;
    boolean reportLocalTemporaries = false;
    final SortedMap<TableMetaDataKey, ArrayList<String>> sortedRows = new TreeMap<>();

    if (null == tableNamePattern) {
        tableNamePattern = "%";
    }//  w ww . j  a  v  a 2 s.c  o m
    if (null == catalog || catalog.length() == 0) {
        catalog = this.connection.getCatalog();
    }
    ArrayList<ArrayList<String>> data = new ArrayList<>();
    try {
        vitessStatement = new VitessStatement(this.connection);
        resultSet = vitessStatement.executeQuery("SHOW FULL TABLES FROM " + this.quotedId + catalog
                + this.quotedId + " LIKE \'" + tableNamePattern + "\'");

        if (null == types || types.length == 0) {
            reportTables = reportViews = reportSystemTables = reportSystemViews = reportLocalTemporaries = true;
        } else {
            for (String type : types) {
                if (TableType.TABLE.equalsTo(type)) {
                    reportTables = true;

                } else if (TableType.VIEW.equalsTo(type)) {
                    reportViews = true;

                } else if (TableType.SYSTEM_TABLE.equalsTo(type)) {
                    reportSystemTables = true;

                } else if (TableType.SYSTEM_VIEW.equalsTo(type)) {
                    reportSystemViews = true;

                } else if (TableType.LOCAL_TEMPORARY.equalsTo(type)) {
                    reportLocalTemporaries = true;
                }
            }
        }

        int typeColumnIndex = 0;
        boolean hasTableTypes;
        try {
            typeColumnIndex = resultSet.findColumn("table_type");
            hasTableTypes = true;
        } catch (SQLException sqlEx) {
            try {
                typeColumnIndex = resultSet.findColumn("Type");
                hasTableTypes = true;
            } catch (SQLException sqlEx2) {
                hasTableTypes = false;
            }
        }

        while (resultSet.next()) {
            ArrayList<String> row = new ArrayList<>();
            row.add(0, catalog);
            row.add(1, null);
            row.add(2, resultSet.getString(1));
            row.add(3, "");
            row.add(4, null);
            row.add(5, null);
            row.add(6, null);
            row.add(7, null);
            row.add(8, null);
            row.add(9, null);

            if (hasTableTypes) {
                String tableType = resultSet.getString(typeColumnIndex);
                switch (TableType.getTableTypeCompliantWith(tableType)) {
                case TABLE:
                    boolean reportTable = false;
                    TableMetaDataKey tablesKey = null;
                    if (reportSystemTables) {
                        row.add(3, TableType.TABLE.toString());
                        tablesKey = new TableMetaDataKey(TableType.TABLE.getName(), catalog, null,
                                resultSet.getString(1));
                        reportTable = true;
                    }
                    if (reportTable) {
                        sortedRows.put(tablesKey, row);
                    }
                    break;

                case VIEW:
                    if (reportViews) {
                        row.add(3, TableType.VIEW.toString());
                        sortedRows.put(new TableMetaDataKey(TableType.VIEW.getName(), catalog, null,
                                resultSet.getString(1)), row);
                    }
                    break;

                case SYSTEM_TABLE:
                    if (reportSystemTables) {
                        row.add(3, TableType.SYSTEM_TABLE.toString());
                        sortedRows.put(new TableMetaDataKey(TableType.SYSTEM_TABLE.getName(), catalog, null,
                                resultSet.getString(1)), row);
                    }
                    break;

                case SYSTEM_VIEW:
                    if (reportSystemViews) {
                        row.add(3, TableType.SYSTEM_VIEW.toString());
                        sortedRows.put(new TableMetaDataKey(TableType.SYSTEM_VIEW.getName(), catalog, null,
                                resultSet.getString(1)), row);
                    }
                    break;

                case LOCAL_TEMPORARY:
                    if (reportLocalTemporaries) {
                        row.add(3, TableType.LOCAL_TEMPORARY.toString());
                        sortedRows.put(new TableMetaDataKey(TableType.LOCAL_TEMPORARY.getName(), catalog, null,
                                resultSet.getString(1)), row);
                    }
                    break;

                default:
                    row.add(3, TableType.TABLE.toString());
                    sortedRows.put(new TableMetaDataKey(TableType.TABLE.getName(), catalog, null,
                            resultSet.getString(1)), row);
                    break;
                }
            } else {
                if (reportTables) {
                    // Pre-MySQL-5.0.1, tables only
                    row.add(3, TableType.TABLE.toString());
                    sortedRows.put(new TableMetaDataKey(TableType.TABLE.getName(), catalog, null,
                            resultSet.getString(1)), row);
                }
            }
            data.add(row);
        }
    } finally {
        if (null != resultSet) {
            resultSet.close();
        }
        if (null != vitessStatement) {
            vitessStatement.close();
        }
    }
    String[] columnNames = new String[] { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE", "REMARKS",
            "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "SELF_REFERENCING_COL_NAME", "REF_GENERATION" };
    Query.Type[] columnTypes = new Query.Type[] { Query.Type.VARCHAR, Query.Type.VARCHAR, Query.Type.VARCHAR,
            Query.Type.VARCHAR, Query.Type.VARCHAR, Query.Type.VARCHAR, Query.Type.VARCHAR, Query.Type.VARCHAR,
            Query.Type.VARCHAR, Query.Type.VARCHAR };

    return new VitessResultSet(columnNames, columnTypes, data, this.connection);
}

From source file:org.apache.bigtop.itest.hive.TestJdbc.java

@Test
public void preparedStmtAndResultSet() throws SQLException {
    final String tableName = "bigtop_jdbc_psars_test_table";
    try (Statement stmt = conn.createStatement()) {
        stmt.execute("drop table if exists " + tableName);
        stmt.execute("create table " + tableName + " (bo boolean, ti tinyint, db double, fl float, "
                + "i int, lo bigint, sh smallint, st varchar(32))");
    }/*w  w w.  j a  va 2  s  . co m*/

    // NOTE Hive 1.2 theoretically support binary, Date & Timestamp in JDBC, but I get errors when I
    // try to put them in the query.
    try (PreparedStatement ps = conn
            .prepareStatement("insert into " + tableName + " values (?, ?, ?, ?, ?, ?, ?, ?)")) {
        ps.setBoolean(1, true);
        ps.setByte(2, (byte) 1);
        ps.setDouble(3, 3.141592654);
        ps.setFloat(4, 3.14f);
        ps.setInt(5, 3);
        ps.setLong(6, 10L);
        ps.setShort(7, (short) 20);
        ps.setString(8, "abc");
        ps.executeUpdate();
    }

    try (PreparedStatement ps = conn.prepareStatement("insert into " + tableName + " (i, st) " + "values(?, ?)",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
        ps.setNull(1, Types.INTEGER);
        ps.setObject(2, "mary had a little lamb");
        ps.executeUpdate();
        ps.setNull(1, Types.INTEGER, null);
        ps.setString(2, "its fleece was white as snow");
        ps.clearParameters();
        ps.setNull(1, Types.INTEGER, null);
        ps.setString(2, "its fleece was white as snow");
        ps.execute();

    }

    try (Statement stmt = conn.createStatement()) {

        ResultSet rs = stmt.executeQuery("select * from " + tableName);

        ResultSetMetaData md = rs.getMetaData();

        int colCnt = md.getColumnCount();
        LOG.debug("Column count is " + colCnt);

        for (int i = 1; i <= colCnt; i++) {
            LOG.debug("Looking at column " + i);
            String strrc = md.getColumnClassName(i);
            LOG.debug("Column class name is " + strrc);

            int intrc = md.getColumnDisplaySize(i);
            LOG.debug("Column display size is " + intrc);

            strrc = md.getColumnLabel(i);
            LOG.debug("Column label is " + strrc);

            strrc = md.getColumnName(i);
            LOG.debug("Column name is " + strrc);

            intrc = md.getColumnType(i);
            LOG.debug("Column type is " + intrc);

            strrc = md.getColumnTypeName(i);
            LOG.debug("Column type name is " + strrc);

            intrc = md.getPrecision(i);
            LOG.debug("Precision is " + intrc);

            intrc = md.getScale(i);
            LOG.debug("Scale is " + intrc);

            boolean boolrc = md.isAutoIncrement(i);
            LOG.debug("Is auto increment? " + boolrc);

            boolrc = md.isCaseSensitive(i);
            LOG.debug("Is case sensitive? " + boolrc);

            boolrc = md.isCurrency(i);
            LOG.debug("Is currency? " + boolrc);

            intrc = md.getScale(i);
            LOG.debug("Scale is " + intrc);

            intrc = md.isNullable(i);
            LOG.debug("Is nullable? " + intrc);

            boolrc = md.isReadOnly(i);
            LOG.debug("Is read only? " + boolrc);

        }

        while (rs.next()) {
            LOG.debug("bo = " + rs.getBoolean(1));
            LOG.debug("bo = " + rs.getBoolean("bo"));
            LOG.debug("ti = " + rs.getByte(2));
            LOG.debug("ti = " + rs.getByte("ti"));
            LOG.debug("db = " + rs.getDouble(3));
            LOG.debug("db = " + rs.getDouble("db"));
            LOG.debug("fl = " + rs.getFloat(4));
            LOG.debug("fl = " + rs.getFloat("fl"));
            LOG.debug("i = " + rs.getInt(5));
            LOG.debug("i = " + rs.getInt("i"));
            LOG.debug("lo = " + rs.getLong(6));
            LOG.debug("lo = " + rs.getLong("lo"));
            LOG.debug("sh = " + rs.getShort(7));
            LOG.debug("sh = " + rs.getShort("sh"));
            LOG.debug("st = " + rs.getString(8));
            LOG.debug("st = " + rs.getString("st"));
            LOG.debug("tm = " + rs.getObject(8));
            LOG.debug("tm = " + rs.getObject("st"));
            LOG.debug("tm was null " + rs.wasNull());
        }
        LOG.debug("bo is column " + rs.findColumn("bo"));

        int intrc = rs.getConcurrency();
        LOG.debug("concurrency " + intrc);

        intrc = rs.getFetchDirection();
        LOG.debug("fetch direction " + intrc);

        intrc = rs.getType();
        LOG.debug("type " + intrc);

        Statement copy = rs.getStatement();

        SQLWarning warning = rs.getWarnings();
        while (warning != null) {
            LOG.debug("Found a warning: " + warning.getMessage());
            warning = warning.getNextWarning();
        }
        rs.clearWarnings();
    }
}

From source file:org.apache.gora.sql.store.SqlStore.java

public T readObject(ResultSet rs, T persistent, String[] requestFields) throws SQLException, IOException {
    if (rs == null) {
        return null;
    }// w w  w.j  ava2s  .  co  m

    for (int i = 0; i < requestFields.length; i++) {
        String f = requestFields[i];
        Field field = fieldMap.get(f);
        Schema fieldSchema = field.schema();
        Type type = fieldSchema.getType();
        Column column = mapping.getColumn(field.name());
        String columnName = column.getName();
        int columnIndex = rs.findColumn(columnName);

        if (rs.getObject(columnIndex) == null) {
            continue;
        }
        switch (type) {
        case MAP:
            readField(rs, columnIndex, persistent.get(field.pos()), fieldSchema, column);
            break;
        case ARRAY:
            readField(rs, columnIndex, persistent.get(field.pos()), fieldSchema, column);
            break;
        case BOOLEAN:
            persistent.put(field.pos(), rs.getBoolean(columnIndex));
            break;
        case BYTES:
            persistent.put(field.pos(), ByteBuffer.wrap(getBytes(rs, columnIndex, fieldSchema, column)));
            break;
        case DOUBLE:
            persistent.put(field.pos(), rs.getDouble(columnIndex));
            break;
        case ENUM:
            Object val = AvroUtils.getEnumValue(fieldSchema, rs.getString(columnIndex));
            persistent.put(field.pos(), val);
            break;
        case FIXED:
            ((SpecificFixed) persistent.get(i)).bytes(getBytes(rs, columnIndex, fieldSchema, column));
            break;
        case FLOAT:
            persistent.put(field.pos(), rs.getFloat(columnIndex));
            break;
        case INT:
            persistent.put(field.pos(), rs.getInt(columnIndex));
            break;
        case LONG:
            persistent.put(field.pos(), rs.getLong(columnIndex));
            break;
        case NULL:
            break;
        case RECORD:
            Object o = readField(rs, columnIndex, persistent.get(field.pos()), fieldSchema, column);
            persistent.put(field.pos(), o);
            break;
        case STRING:
            persistent.put(field.pos(), new Utf8(rs.getString(columnIndex)));
            break;
        case UNION:
            throw new IOException("Union is not supported yet");
        }
        persistent.setDirty(field.pos());
    }
    persistent.clearDirty();
    return persistent;
}

From source file:org.apache.hadoop.chukwa.database.TestDatabaseWebJson.java

protected void verifyTableData(String table) {
    Calendar startCalendar = new GregorianCalendar();
    // startCalendar.add(Calendar.HOUR_OF_DAY,-1);
    startCalendar.add(Calendar.MINUTE, -30);
    long startTime = startCalendar.getTime().getTime();

    Calendar endCalendar = new GregorianCalendar();
    // endCalendar.add(Calendar.HOUR_OF_DAY,1);
    long endTime = endCalendar.getTime().getTime();

    String url = data_url + "?table=" + table + "&start=" + startTime + "&end=" + endTime;
    System.out.println(url);//  www .ja  v a 2 s. c  om

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);

    try {

        /*
         * 1. get the json result for the specified table
         */
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("Http Error: " + method.getStatusLine());
        }
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(method.getResponseBodyAsStream(), method.getResponseCharSet()));
        String json_str = "";
        String str;
        while ((str = reader.readLine()) != null) {
            json_str += str;
        }

        /*
         * 2. convert the json string to individual field and compare it 
         * with the database
         */

        String cluster = "demo";
        DatabaseWriter db = new DatabaseWriter(cluster);

        JSONArray json_array = new JSONArray(json_str);
        for (int i = 0; i < json_array.length(); i++) {
            JSONObject row_obj = json_array.getJSONObject(i);

            // get the database row

            String queryString = getDatabaseQuery(table, row_obj);
            Macro m = new Macro(startTime, endTime, queryString);
            ResultSet rs = db.query(m.toString());
            // move to the first record
            rs.next();
            ResultSetMetaData md = rs.getMetaData();
            Iterator names = row_obj.keys();
            while (names.hasNext()) {
                String name = (String) names.next();
                String jsonValue = (String) row_obj.get(name);
                String dbValue = rs.getString(name);
                int dbCol = rs.findColumn(name);
                int dbType = md.getColumnType(dbCol);
                if (dbType == 93) {
                    // timestamp
                    dbValue = Long.toString(rs.getTimestamp(name).getTime());
                }
                // System.out.println("compare "+name+":"+dbType+":"+dbValue+":"+jsonValue);
                assertEquals(dbValue, jsonValue);
            }
        }

        db.close();
    } catch (SQLException e) {
        System.out.println("Exception: " + e.toString() + ":" + e.getMessage());
        System.out.println("Exception: " + e.toString() + ":" + e.getSQLState());
        System.out.println("Exception: " + e.toString() + ":" + e.getErrorCode());
        fail("SQL Error:" + ExceptionUtil.getStackTrace(e));
    } catch (Exception eOther) {
        System.out.println("Other Exception: " + eOther.toString());
        eOther.printStackTrace();
        fail("Error:" + ExceptionUtil.getStackTrace(eOther));
    } finally {
    }
}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

@Test
public void testResultSetColumnNameCaseInsensitive() throws SQLException {
    Statement stmt = con.createStatement();
    ResultSet res;

    res = stmt.executeQuery("select c1 from " + dataTypeTableName + " limit 1");
    try {// w w  w.j  a v a2  s . co m
        int count = 0;
        while (res.next()) {
            res.findColumn("c1");
            res.findColumn("C1");
            count++;
        }
        assertEquals(count, 1);
    } catch (Exception e) {
        String msg = "Unexpected exception: " + e;
        LOG.info(msg, e);
        fail(msg);
    }

    res = stmt.executeQuery("select c1 C1 from " + dataTypeTableName + " limit 1");
    try {
        int count = 0;
        while (res.next()) {
            res.findColumn("c1");
            res.findColumn("C1");
            count++;
        }
        assertEquals(count, 1);
    } catch (Exception e) {
        String msg = "Unexpected exception: " + e;
        LOG.info(msg, e);
        fail(msg);
    }
}

From source file:org.apache.openaz.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver.java

/**
 * Creates an {@link org.apache.openaz.xacml.api.Attribute} from the value associated with the field with
 * the given <code>fieldName</code>.
 *
 * @param resultSet the {@link java.sql.ResultSet} containing the current row from the database
 * @param fieldName the <code>String</code> name of the field containing the attribute value
 * @param pipRequestAttribute the {@link org.apache.openaz.xacml.api.pip.PIPRequest} for the
 *            <code>Attribute</code> to create
 * @return a new <code>Attribute</code> with the value of the given <code>fieldName</code>.
 *///w  w  w  . j ava  2 s  . c o  m
protected Attribute getAttributeFromResultSet(ResultSet resultSet, String fieldName,
        PIPRequest pipRequestAttribute) {
    AttributeValue<?> attributeValue = null;
    Identifier identifierDataType = pipRequestAttribute.getDataTypeId();
    try {
        DataType<?> dataType = dataTypeFactory.getDataType(identifierDataType);
        if (dataType == null) {
            this.logger.warn("Unknown data type " + pipRequestAttribute.getDataTypeId().stringValue());
            return null;
        }
        /*
         * Try to find the column index
         */

        int columnIndex = -1;

        try {
            columnIndex = resultSet.findColumn(fieldName);
        } catch (Exception e) {
            /*
             * The field name could be an integer, let's try that
             */
            try {
                columnIndex = Integer.parseInt(fieldName);
            } catch (Exception e1) {
                logger.error("Failed to find column with label " + fieldName);
            }
        }
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Column " + fieldName + " maps to column index " + columnIndex);
        }

        /*
         * Catch special cases for database types
         */
        if (identifierDataType.equals(XACML3.ID_DATATYPE_BOOLEAN)) {
            attributeValue = dataType.createAttributeValue(resultSet.getBoolean(columnIndex));
        } else if (identifierDataType.equals(XACML3.ID_DATATYPE_DATE)
                || identifierDataType.equals(XACML3.ID_DATATYPE_DATETIME)) {
            attributeValue = dataType.createAttributeValue(resultSet.getDate(columnIndex));
        } else if (identifierDataType.equals(XACML3.ID_DATATYPE_DOUBLE)) {
            attributeValue = dataType.createAttributeValue(resultSet.getDouble(columnIndex));
        } else if (identifierDataType.equals(XACML3.ID_DATATYPE_INTEGER)) {
            attributeValue = dataType.createAttributeValue(resultSet.getInt(columnIndex));
        } else {
            /*
             * Default to convert the string value from the database to the requested data type
             */
            String stringValue = resultSet.getString(columnIndex);
            if (stringValue != null) {
                attributeValue = dataType.createAttributeValue(stringValue);
            }
        }
    } catch (Exception ex) {
        this.logger.error("Exception getting value for fieldName '" + fieldName + "' as a "
                + identifierDataType.stringValue() + ": " + ex.toString(), ex);
        return null;
    }
    String issuer = this.defaultIssuer;
    if (pipRequestAttribute.getIssuer() != null) {
        issuer = pipRequestAttribute.getIssuer();
    }
    return new StdAttribute(pipRequestAttribute.getCategory(), pipRequestAttribute.getAttributeId(),
            attributeValue, issuer, false);
}

From source file:org.easyrec.utils.spring.store.dao.DaoUtils.java

/**
 * get a Long object from a result set column with given name or null if no such
 * column exists in the result set/*w w  w  .j a  v  a2  s .  co  m*/
 *
 * @param rs
 * @param columnName
 * @return the value, which may be <code>null</code>
 * @throws SQLException
 */
public static Long getLongIfPresent(ResultSet rs, String columnName) throws SQLException {
    try {
        rs.findColumn(columnName);
    } catch (SQLException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "getLong() failed for column '" + columnName + "'. ResultSet doesn't contain that column");
        }
        return null;
    }
    return getLong(rs, columnName);
}