Example usage for java.sql ResultSet getObject

List of usage examples for java.sql ResultSet getObject

Introduction

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

Prototype

Object getObject(String columnLabel) throws SQLException;

Source Link

Document

Gets the value of the designated column in the current row of this ResultSet object as an Object in the Java programming language.

Usage

From source file:common.dao.impl.BaseDAOImpl.java

public List<Map<String, Object>> callQueryProcedure(final String sql, final Object[] params) {
    logger.debug("start to call procedure" + sql + ", params is " + params);
    final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    getCurrentSession().doWork(new Work() {
        public void execute(Connection conn) throws SQLException {
            CallableStatement cs = conn.prepareCall(sql);
            if (params != null) {
                logger.debug("params is not null it's members is " + Arrays.asList(params));
                for (int i = 0; i < params.length; i++) {
                    cs.setObject(i + 1, params[i]);
                }/*  w w w  .  j  a v a  2  s  .co m*/
            } else
                logger.debug("params is null");
            ResultSet rs = cs.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int colCount = metaData.getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 1; i <= colCount; i++) {
                    String colName = metaData.getColumnName(i);
                    map.put(colName, rs.getObject(colName));
                }
                result.add(map);
            }
            rs.close();
            cs.close();
        }
    });
    return result;
}

From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java

public <T, S> HashMap<T, S> getRecordsAsHashmap(String sql, Object[] params, Class[] returnTypes) {
    PreparedStatement st = null;/*from   w ww  . j a v  a  2  s . c  o m*/
    ResultSet rs = null;
    ResultSetMetaData rsMetaData = null;
    try {
        HashMap<T, S> records = new HashMap<>();
        st = conn.prepareStatement(sql);
        setParams(st, params);
        rs = st.executeQuery();
        while (rs.next()) {
            if (returnTypes != null)
                records.put((T) convertType(rs.getObject(1), returnTypes[0]),
                        (S) convertType(rs.getObject(2), returnTypes[1]));
            else
                records.put((T) rs.getObject(1), (S) rs.getObject(2));
        }
        return records;
    } catch (Exception ex) {
        throw new NativeQueryException(sql, null, ex);
    } finally {
        closeOnFinally(rs, st);
    }

}

From source file:de.iritgo.aktario.jdbc.LoadObject.java

/**
 * Load an object.//from  w  ww.j av  a  2s.  c o m
 *
 * @param dataSource The data source to load from.
 * @param typeId The type of the object to load.
 * @param uniqueId The unique id of the object to load.
 * @return The loaded object (already registered with the base registry).
 */
private DataObject load(final DataSource dataSource, final String typeId, long uniqueId) {
    DataObject object = null;

    try {
        QueryRunner query = new QueryRunner(dataSource);

        object = (DataObject) query.query("select * from " + typeId + " where id=" + uniqueId,
                new ResultSetHandler() {
                    public Object handle(ResultSet rs) throws SQLException {
                        rs.getMetaData();

                        if (rs.next()) {
                            try {
                                DataObject object = (DataObject) Engine.instance().getIObjectFactory()
                                        .newInstance(typeId);

                                object.setUniqueId(rs.getLong("id"));

                                for (Iterator i = object.getAttributes().entrySet().iterator(); i.hasNext();) {
                                    Map.Entry attribute = (Map.Entry) i.next();

                                    if (attribute.getValue() instanceof IObjectList) {
                                        loadList(dataSource, object,
                                                object.getIObjectListAttribute((String) attribute.getKey()));
                                    } else {
                                        try {
                                            if (!object.getAttribute((String) attribute.getKey()).getClass()
                                                    .equals(rs.getObject((String) attribute.getKey())
                                                            .getClass())) {
                                                System.out.println(
                                                        "********* Datastruct is not compatible with dataobject:"
                                                                + object.getTypeId() + ":" + attribute.getKey()
                                                                + " Types:"
                                                                + object.getAttribute(
                                                                        (String) attribute.getKey()).getClass()
                                                                + "!="
                                                                + rs.getObject((String) attribute.getKey())
                                                                        .getClass());
                                            }

                                            object.setAttribute((String) attribute.getKey(),
                                                    rs.getObject((String) attribute.getKey()));
                                        } catch (NullPointerException x) {
                                            System.out.println("LoadObject error: " + attribute.getKey());
                                        }
                                    }
                                }

                                return object;
                            } catch (NoSuchIObjectException ignored) {
                                Log.logError("persist", "LoadObject", "NoSuchIObjectException");
                            }
                        } else {
                        }

                        return null;
                    }
                });

        if (object != null) {
            Log.logVerbose("persist", "LoadObject", "Successfully loaded object " + typeId + ":" + uniqueId);
        } else {
            Log.logError("persist", "LoadObject", "Unable to find object " + typeId + ":" + uniqueId);
        }
    } catch (SQLException x) {
        Log.logError("persist", "LoadObject",
                "Error while loading the object " + typeId + ":" + uniqueId + ": " + x);
    }

    return object;
}

From source file:com.mapd.bench.BenchmarkCloud.java

String executeQuery(Connection conn1, String qid, String sql, int iterations) {
    Statement stmt = null;// w w  w  .  j av  a2  s.  co  m
    Connection conn = getConnection(url, iUser, iPasswd);

    Long firstExecute = 0l;
    Long firstJdbc = 0l;
    Long firstIterate = 0l;

    DescriptiveStatistics statsExecute = new DescriptiveStatistics();
    DescriptiveStatistics statsJdbc = new DescriptiveStatistics();
    DescriptiveStatistics statsIterate = new DescriptiveStatistics();
    DescriptiveStatistics statsTotal = new DescriptiveStatistics();

    long totalTime = 0;
    int resultCount = 0;
    try {

        long startTime = System.currentTimeMillis();
        for (int loop = 0; loop < iterations; loop++) {

            //Execute a query
            stmt = conn.createStatement();

            long timer = System.currentTimeMillis();
            if (loop == 0) {
                System.out.println(String.format("Query Id is %s : query is '%s'", qid, sql));
            }
            ResultSet rs = stmt.executeQuery(sql);

            long executeTime = 0;
            long jdbcTime = 0;

            // gather internal execute time for MapD as we are interested in that
            if (driver.equals(JDBC_DRIVER)) {
                executeTime = stmt.getQueryTimeout();
                jdbcTime = (System.currentTimeMillis() - timer) - executeTime;
            } else {
                jdbcTime = (System.currentTimeMillis() - timer);
                executeTime = 0;
            }
            // this is fake to get our intenal execute time.
            logger.debug("Query Timeout/AKA internal Execution Time was " + stmt.getQueryTimeout()
                    + " ms Elapsed time in JVM space was " + (System.currentTimeMillis() - timer) + "ms");

            timer = System.currentTimeMillis();
            //Extract data from result set
            resultCount = 0;
            while (rs.next()) {
                Object obj = rs.getObject(1);
                if (obj != null && obj.equals(statsExecute)) {
                    logger.info("Impossible");
                }
                resultCount++;
            }
            long iterateTime = (System.currentTimeMillis() - timer);

            //        if (resultCount != expected) {
            //          logger.error("Expect " + expected + " actual " + resultCount + " for query " + sql);
            //          // don't run anymore
            //          break;
            //        }
            if (loop == 0) {
                firstJdbc = jdbcTime;
                firstExecute = executeTime;
                firstIterate = iterateTime;

            } else {
                statsJdbc.addValue(jdbcTime);
                statsExecute.addValue(executeTime);
                statsIterate.addValue(iterateTime);
                statsTotal.addValue(jdbcTime + executeTime + iterateTime);
            }

            //Clean-up environment
            rs.close();
            stmt.close();
        }
        totalTime = System.currentTimeMillis() - startTime;
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
        System.exit(4);
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
        System.exit(3);
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
            System.exit(6);
        } //end finally try
    } //end try

    // write it to the db here as well
    String insertPart = String.format(insertDescriptor, this.rid, this.rTimestamp, url, this.driver, label,
            gpuCount, this.tableName, qid, resultCount, "", statsTotal.getMean(), statsTotal.getMin(),
            statsTotal.getMax(), statsTotal.getPercentile(85), statsExecute.getMean(), statsExecute.getMin(),
            statsExecute.getMax(), statsExecute.getPercentile(85), statsExecute.getPercentile(25),
            statsExecute.getStandardDeviation(), statsJdbc.getMean(), statsJdbc.getMin(), statsJdbc.getMax(),
            statsJdbc.getPercentile(85), statsIterate.getMean(), statsIterate.getMin(), statsIterate.getMax(),
            statsIterate.getPercentile(85), firstExecute, firstJdbc, firstIterate, iterations, totalTime,
            (long) statsTotal.getSum() + firstExecute + firstJdbc + firstIterate, targetDBVersion);

    LResult.add("Insert into results values " + insertPart);

    return String.format(lineDescriptor, qid, statsTotal.getMean(), statsTotal.getMin(), statsTotal.getMax(),
            statsTotal.getPercentile(85), statsExecute.getMean(), statsExecute.getMin(), statsExecute.getMax(),
            statsExecute.getPercentile(85), statsExecute.getPercentile(25), statsExecute.getStandardDeviation(),
            statsJdbc.getMean(), statsJdbc.getMin(), statsJdbc.getMax(), statsJdbc.getPercentile(85),
            statsIterate.getMean(), statsIterate.getMin(), statsIterate.getMax(),
            statsIterate.getPercentile(85), firstExecute, firstJdbc, firstIterate, iterations, totalTime,
            (long) statsTotal.getSum() + firstExecute + firstJdbc + firstIterate);

}

From source file:com.intellectualcrafters.plot.database.SQLManager.java

/**
 * @param id/*from ww  w . ja  v a  2s .  co  m*/
 * @return
 */
@Override
public HashMap<String, Object> getSettings(final int id) {
    final HashMap<String, Object> h = new HashMap<String, Object>();
    PreparedStatement stmt = null;
    try {
        stmt = connection
                .prepareStatement("SELECT * FROM `" + prefix + "plot_settings` WHERE `plot_plot_id` = ?");
        stmt.setInt(1, id);
        final ResultSet r = stmt.executeQuery();
        String var;
        Object val;
        while (r.next()) {
            var = "biome";
            val = r.getObject(var);
            h.put(var, val);
            var = "rain";
            val = r.getObject(var);
            h.put(var, val);
            var = "custom_time";
            val = r.getObject(var);
            h.put(var, val);
            var = "time";
            val = r.getObject(var);
            h.put(var, val);
            var = "deny_entry";
            val = r.getObject(var);
            h.put(var, (short) 0);
            var = "alias";
            val = r.getObject(var);
            h.put(var, val);
            var = "position";
            val = r.getObject(var);
            h.put(var, val);
            var = "flags";
            val = r.getObject(var);
            h.put(var, val);
            var = "merged";
            val = r.getObject(var);
            h.put(var, val);
        }
        stmt.close();
        ;
    } catch (final SQLException e) {
        Logger.add(LogLevel.WARNING, "Failed to load settings for plot: " + id);
        e.printStackTrace();
    }
    return h;
}

From source file:com.iih5.smartorm.model.Model.java

/**
 * Model/*  ww w  .ja  va 2 s .  co  m*/
 *
 * @param columns        ?? columns="id,name,age"
 * @param conditions     ? conditions="user_id=? and age=?"
 * @param conditionParas ??
 * @param <T>
 * @return Model
 * @
 */
<T> List<T> queryList(String columns, String conditions, Object[] conditionParas) {
    String sql = DefaultDialect.getDialect().forModelFindBy(table, columns, conditions);
    final Set<String> columnMeta = new HashSet<String>();
    return jdbc.query(sql, conditionParas, new RowMapper<T>() {
        public T mapRow(ResultSet rs, int rowNum) throws SQLException {
            try {
                if (columnMeta.size() == 0) {
                    for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
                        String column = rs.getMetaData().getColumnLabel(i + 1);
                        columnMeta.add(column);
                    }
                }
                Model<?> mModel = getUsefulClass().newInstance();
                Field[] fields = mModel.getClass().getFields();
                if (fields.length > 0) {
                    for (Field f : fields) {
                        if (columnMeta.contains(f.getName())) {
                            f.set(mModel, rs.getObject(f.getName()));
                        }
                    }
                } else {
                    ResultSetMetaData rsmd = rs.getMetaData();
                    int columnCount = rsmd.getColumnCount();
                    Map<String, Object> attrs = mModel.getAttrs();
                    for (int i = 1; i <= columnCount; i++) {
                        Object value = rs.getObject(i);
                        if (value != null) {
                            attrs.put(rsmd.getColumnLabel(i), value);
                        }
                    }
                }
                return (T) mModel;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });
}

From source file:com.vangent.hieos.logbrowser.util.TableModel.java

public TableModel(String sqlRequest, Map fieldsAndFormats, Connection c) throws SQLException {
    this.fieldsAndFormats = fieldsAndFormats;
    ResultSet statementResult;
    log.debug("TABLE_MODEL_SYSLOG: database connection created\n");

    Statement statement = c.createStatement();
    log.debug("TABLE_MODEL_SYSLOG: statement created\n");
    statementResult = statement.executeQuery(sqlRequest);
    log.debug("TABLE_MODEL_SYSLOG: Query executed\n");
    log.debug("<--" + new GregorianCalendar().getTime() + " TableModel close Database \n");

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

    dataVector = new Vector<Vector<Object>>();
    headerVector = new Vector<String>();

    log.debug("TABLE_MODEL_SYSLOG: colomn count : " + columnCount + "\n");
    log.debug("TABLE_MODEL_SYSLOG: Table--------------------------------------");
    for (int i = 0; i < columnCount; i++) {
        headerVector.add(metaData.getColumnName((i + 1)));
        log.debug(metaData.getColumnName((i + 1)) + "\t");
    }/*w w  w .j a va 2 s .c o m*/

    while (statementResult.next()) {
        Vector<Object> tmp = new Vector<Object>(columnCount);
        for (int j = 0; j < columnCount; j++) {
            String columnName = getColumnName(j);
            Object columnData = statementResult.getObject(columnName);
            columnData = getFormattedData(columnName, columnData);
            tmp.add(columnData);
            log.debug(columnData + "\t");
        }
        log.debug("\n");
        dataVector.add(tmp);
    }
}

From source file:cosmos.sql.TestSql.java

@Test
public void testNoLimit() throws SQLException {
    loadDriverClass();//  www  . j  av  a2s . c  om
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery(
                "select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS + "\".\"" + meataData.uuid() + "\"");

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

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        SortedSet<String> sets = Sets.newTreeSet();
        for (int i = 0; i < 10; i++) {
            sets.add(Integer.valueOf(i).toString());
        }
        Queue<String> values = Lists.newLinkedList(sets);

        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            @SuppressWarnings("unchecked")
            List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet
                    .getObject("PAGE_ID");
            assertEquals(sValues.size(), 1);
            RecordValue<?> onlyValue = sValues.iterator().next().getValue();
            assertEquals(onlyValue.visibility().toString(), "[en]");
            values.remove(onlyValue.value());
            resultsFound++;

        }

        assertEquals(resultsFound, 10);
        assertEquals(values.size(), 0);
    } finally {
        close(connection, statement);
    }
}

From source file:computer_store.GUI.java

private void fillSysTable(javax.swing.JTable table, java.sql.ResultSet rs) {
    try {//from w  w  w . ja v  a 2 s. co  m

        //To remove previously added rows
        while (table.getRowCount() > 0) {
            ((javax.swing.table.DefaultTableModel) table.getModel()).removeRow(0);
        }
        int columns = rs.getMetaData().getColumnCount();
        int rows = 0;
        //Adding column headers
        Object[] ids = new Object[columns];
        for (int i = 1; i <= columns; i++) {
            ids[i - 1] = rs.getMetaData().getColumnName(i);
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).setColumnIdentifiers(ids);
        java.util.ArrayList<String> systems = new java.util.ArrayList();
        //Adding rows from ResultSet
        while (rs.next()) {
            systems.add(rs.getString(1));
            Object[] row = new Object[columns];
            for (int i = 1; i <= columns; i++) {
                row[i - 1] = rs.getObject(i);
            }
            ((javax.swing.table.DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
            rows++;
        }
        //Adding new column with prices
        Object[] prices = new Object[rows];
        for (int i = 0; i < prices.length; i++) {
            prices[i] = handler.getSystemPrice(systems.get(i));
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).addColumn("Price", prices);
        //Adding new column with selling prices
        Object[] sellPrices = new Object[rows];
        for (int i = 0; i < sellPrices.length; i++) {
            sellPrices[i] = handler.getSystemSellPrice(systems.get(i));
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).addColumn("Selling price", sellPrices);
        //Adding new column with current stock
        Object[] inStock = new Object[rows];
        for (int i = 0; i < prices.length; i++) {
            inStock[i] = handler.systemsInStock(systems.get(i));
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).addColumn("In stock", inStock);

        rs.close();
    } catch (Exception e) {
        System.out.print(e);
    }
}

From source file:com.globalsight.ling.tm3.core.TuStorage.java

private List<TuData<T>> getTuData(Connection conn, List<Long> ids, boolean locking) throws SQLException {
    StatementBuilder sb = new StatementBuilder("SELECT ").append("tmId, id, srcLocaleId");
    for (TM3Attribute attr : getStorage().getInlineAttributes()) {
        sb.append(", ").append(attr.getColumnName());
    }/*from  w  ww .j  av  a 2 s .  co m*/
    sb.append(" FROM ").append(getStorage().getTuTableName()).append(" WHERE id IN")
            .append(SQLUtil.longGroup(ids)).append(" ORDER BY id");

    try {
        PreparedStatement ps = sb.toPreparedStatement(conn);
        ResultSet rs = SQLUtil.execQuery(ps);

        List<TuData<T>> tuDatas = new ArrayList<TuData<T>>();
        while (rs.next()) {
            TuData<T> tu = new TuData<T>();
            tu.tmId = rs.getLong(1);
            tu.id = rs.getLong(2);
            tu.srcLocaleId = rs.getLong(3);
            int pos = 4;
            for (TM3Attribute attr : getStorage().getInlineAttributes()) {
                Object val = rs.getObject(pos++);
                if (val != null) {
                    tu.attrs.put(attr, val);
                }
            }
            tuDatas.add(tu);
        }
        ps.close();
        return tuDatas;
    } catch (Exception e) {
        throw new SQLException(e);
    }
}