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:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

public <T, S> HashMap<T, S> getRecordsAsHashmap(String sql, Object[] params, Class[] returnTypes) {
    PreparedStatement st = null;//from ww  w .  j ava 2s  .com
    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) ConversionUtility.convertType(rs.getObject(1), returnTypes[0]),
                        (S) ConversionUtility.convertType(rs.getObject(2), returnTypes[1]));
            else
                records.put((T) rs.getObject(1), (S) rs.getObject(2));
        }
        return records;
    } catch (Exception ex) {
        throw new DataQueryException(sql, null, ex);
    } finally {
        closeOnFinally(rs, st);
    }

}

From source file:com.greatmancode.craftconomy3.utils.OldFormatConverter.java

public void run() throws SQLException, IOException, ParseException {
    String dbType = Common.getInstance().getMainConfig().getString("System.Database.Type");
    HikariConfig config = new HikariConfig();
    if (dbType.equalsIgnoreCase("mysql")) {
        config.setMaximumPoolSize(10);//from   w  w  w  .ja v  a 2 s  . com
        config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
        config.addDataSourceProperty("serverName",
                Common.getInstance().getMainConfig().getString("System.Database.Address"));
        config.addDataSourceProperty("port",
                Common.getInstance().getMainConfig().getString("System.Database.Port"));
        config.addDataSourceProperty("databaseName",
                Common.getInstance().getMainConfig().getString("System.Database.Db"));
        config.addDataSourceProperty("user",
                Common.getInstance().getMainConfig().getString("System.Database.Username"));
        config.addDataSourceProperty("password",
                Common.getInstance().getMainConfig().getString("System.Database.Password"));
        config.addDataSourceProperty("autoDeserialize", true);
        config.setConnectionTimeout(5000);
        db = new HikariDataSource(config);

    } else if (dbType.equalsIgnoreCase("sqlite")) {
        config.setDriverClassName("org.sqlite.JDBC");
        config.setJdbcUrl("jdbc:sqlite:" + Common.getInstance().getServerCaller().getDataFolder()
                + File.separator + "database.db");
        db = new HikariDataSource(config);
    } else {
        Common.getInstance().sendConsoleMessage(Level.SEVERE,
                "Unknown database type for old format converter!");
        return;
    }
    Connection connection = db.getConnection();
    this.tablePrefix = Common.getInstance().getMainConfig().getString("System.Database.Prefix");

    File accountFile = new File(Common.getInstance().getServerCaller().getDataFolder(), "accounts.json");

    Common.getInstance().sendConsoleMessage(Level.INFO,
            "Doing a backup in a xml file before doing the conversion.");
    //Document setup
    JSONObject mainObject = new JSONObject();

    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving currency table");
    //Currencies
    PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "currency");
    ResultSet set = statement.executeQuery();
    JSONArray array = new JSONArray();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("id", set.getInt("id"));
        entry.put("name", set.getString("name"));
        entry.put("plural", set.getString("plural"));
        entry.put("minor", set.getString("minor"));
        entry.put("minorPlural", set.getString("minorPlural"));
        entry.put("sign", set.getString("sign"));
        entry.put("status", set.getBoolean("status"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("currencies", array);

    //World groups
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving world group table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "worldgroup");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("groupName", set.getString("groupName"));
        entry.put("worldList", set.getString("worldList"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("worldgroups", array);

    //Exchange table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving exchange table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "exchange");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("from_currency_id", set.getInt("from_currency_id"));
        entry.put("to_currency_id", set.getInt("to_currency_id"));
        entry.put("amount", set.getDouble("amount"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("exchanges", array);

    //config table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving config table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "config");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("name", set.getString("name"));
        entry.put("value", set.getString("value"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("configs", array);

    //account table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving account table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "account");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("name", set.getString("name"));
        entry.put("infiniteMoney", set.getBoolean("infiniteMoney"));
        entry.put("ignoreACL", set.getBoolean("ignoreACL"));
        entry.put("uuid", set.getString("uuid"));

        JSONArray balanceArray = new JSONArray();
        PreparedStatement internalStatement = connection
                .prepareStatement("SELECT * FROM " + tablePrefix + "balance WHERE username_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        ResultSet internalSet = internalStatement.executeQuery();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("currency_id", internalSet.getInt("currency_id"));
            object.put("worldName", internalSet.getString("worldName"));
            object.put("balance", internalSet.getDouble("balance"));
            balanceArray.add(object);
        }
        internalStatement.close();
        entry.put("balances", balanceArray);

        internalStatement = connection
                .prepareStatement("SELECT * FROM " + tablePrefix + "log WHERE username_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        internalSet = internalStatement.executeQuery();
        JSONArray logArray = new JSONArray();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("type", internalSet.getObject("type"));
            object.put("cause", internalSet.getObject("cause"));
            object.put("timestamp", internalSet.getTimestamp("timestamp"));
            object.put("causeReason", internalSet.getString("causeReason"));
            object.put("currencyName", internalSet.getString("currencyName"));
            object.put("worldName", internalSet.getString("worldName"));
            object.put("amount", internalSet.getDouble("amount"));
            logArray.add(object);
        }
        internalStatement.close();
        entry.put("logs", logArray);

        internalStatement = connection
                .prepareStatement("SELECT * FROM " + tablePrefix + "acl WHERE account_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        internalSet = internalStatement.executeQuery();
        JSONArray aclArray = new JSONArray();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("playerName", internalSet.getString("playerName"));
            object.put("deposit", internalSet.getBoolean("deposit"));
            object.put("withdraw", internalSet.getBoolean("withdraw"));
            object.put("acl", internalSet.getBoolean("acl"));
            object.put("balance", internalSet.getBoolean("balance"));
            object.put("owner", internalSet.getBoolean("owner"));
            aclArray.add(object);

        }
        internalStatement.close();
        entry.put("acls", aclArray);
        array.add(entry);
    }
    statement.close();
    mainObject.put("accounts", array);
    Common.getInstance().sendConsoleMessage(Level.INFO, "Writing json file");
    FileWriter writer = new FileWriter(accountFile);
    writer.write(mainObject.toJSONString());
    writer.flush();
    writer.close();
    Common.getInstance().sendConsoleMessage(Level.INFO, "File written! Dropping all tables");
    //The backup is now saved. Let's drop everything
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "config");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "acl");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "balance");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "log");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "worldgroup");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "exchange");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "account");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "currency");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "payday");
    statement.execute();
    statement.close();

    connection.close();
    step2();

}

From source file:com.ccl.jersey.codegen.SimpleMetaDataExporter.java

private void handleColumn(EntityType classModel, String tableName, ResultSet columns) throws SQLException {
    String columnName = normalize(columns.getString("COLUMN_NAME"));
    String normalizedColumnName = namingStrategy.normalizeColumnName(columnName);
    int columnType = columns.getInt("DATA_TYPE");
    String typeName = columns.getString("TYPE_NAME");
    Number columnSize = (Number) columns.getObject("COLUMN_SIZE");
    Number columnDigits = (Number) columns.getObject("DECIMAL_DIGITS");
    int columnIndex = columns.getInt("ORDINAL_POSITION");
    int nullable = columns.getInt("NULLABLE");
    String remarks = columns.getString("REMARKS");
    String defaultValue = columns.getString("COLUMN_DEF");

    String propertyName = namingStrategy.getPropertyName(normalizedColumnName, classModel);

    Map<String, DictType> stringDictTypeMap = registerDictTypes.get(tableName);
    if (null != stringDictTypeMap) {
        DictType dictType = stringDictTypeMap.get(columnName);
        if (null != dictType) {
            String modelClassName = tableModelMapper.get(tableName);
            registerVoDataType(modelClassName, propertyName, dictType.getDictType());
        }/*  w ww.  j  a v  a 2 s  .  c  o  m*/
    }

    Class<?> clazz = configuration.getJavaType(columnType, typeName,
            columnSize != null ? columnSize.intValue() : 0, columnDigits != null ? columnDigits.intValue() : 0,
            tableName, columnName);
    if (clazz == null) {
        throw new IllegalStateException("Found no mapping for " + columnType + " (" + tableName + "."
                + columnName + " " + typeName + ")");
    }

    TypeCategory fieldType = TypeCategory.get(clazz.getName());
    if (Number.class.isAssignableFrom(clazz)) {
        fieldType = TypeCategory.NUMERIC;
    } else if (Enum.class.isAssignableFrom(clazz)) {
        fieldType = TypeCategory.ENUM;
    }
    Type typeModel = new ClassType(fieldType, clazz);
    Property property = createProperty(classModel, normalizedColumnName, propertyName, propertyName, typeModel);
    if (null != defaultValue)
        property.setDefaultValue(DataTypeConvertUtils.convert(defaultValue, clazz));
    ColumnMetadata column = ColumnMetadata.named(normalizedColumnName).ofType(columnType)
            .withIndex(columnIndex);
    if (nullable == DatabaseMetaData.columnNoNulls) {
        column = column.notNull();
    }
    if (columnSize != null) {
        column = column.withSize(columnSize.intValue());
    }
    if (columnDigits != null) {
        column = column.withDigits(columnDigits.intValue());
    }
    property.getData().put("COLUMN", column);

    if (columnAnnotations) {
        property.addAnnotation(new ColumnImpl(normalizedColumnName));
    }
    if (validationAnnotations) {
        if (nullable == DatabaseMetaData.columnNoNulls) {
            NotNullImpl annotation = new NotNullImpl();
            property.addAnnotation(annotation);
        }
        int size = columns.getInt("COLUMN_SIZE");
        if (size > 0 && clazz.equals(String.class)) {
            property.addAnnotation(new SizeImpl(0, size));
        }
    }

    LabelImpl label = new LabelImpl(StringUtils.isBlank(remarks) ? propertyName : remarks);
    property.addAnnotation(label);

    classModel.addProperty(property);
}

From source file:au.com.ish.derbydump.derbydump.metadata.Column.java

/**
 * Get a string value for the value in this column in the datarow
 * //from  w ww.  j av  a2s  . c  om
 * @param dataRow The row which we are exporting
 * @return an SQL statement compliant string version of the value
 */
public String toString(ResultSet dataRow) throws SQLException {

    switch (getColumnDataType()) {
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.BLOB: {
        Blob obj = dataRow.getBlob(columnName);
        return (obj == null) ? "NULL" : processBinaryData(obj);
    }

    case Types.CLOB: {
        Clob obj = dataRow.getClob(columnName);
        return (obj == null) ? "NULL" : processClobData(obj);
    }

    case Types.CHAR:
    case Types.LONGNVARCHAR:
    case Types.VARCHAR: {
        String obj = dataRow.getString(columnName);
        return (obj == null) ? "NULL" : processStringData(obj);
    }

    case Types.TIME: {
        Time obj = dataRow.getTime(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.DATE: {
        Date obj = dataRow.getDate(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.TIMESTAMP: {
        Timestamp obj = dataRow.getTimestamp(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.SMALLINT: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.BIGINT: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.INTEGER: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.NUMERIC:
    case Types.DECIMAL: {
        BigDecimal obj = dataRow.getBigDecimal(columnName);
        return (obj == null) ? "NULL" : String.valueOf(obj);
    }

    case Types.REAL:
    case Types.FLOAT: {
        Float obj = dataRow.getFloat(columnName);
        // dataRow.getFloat() always returns a value. only way to check the null is wasNull() method
        return (dataRow.wasNull()) ? "NULL" : String.valueOf(obj);
    }

    case Types.DOUBLE: {
        Double obj = dataRow.getDouble(columnName);
        return (dataRow.wasNull()) ? "NULL" : String.valueOf(obj);
    }

    default: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }
    }
}

From source file:com.itemanalysis.jmetrik.graph.nicc.NonparametricCurveAnalysis.java

public void evaluateAll() throws SQLException {
    categoryRegression = new TreeMap<VariableAttributes, KernelRegressionCategories>();
    for (VariableAttributes v : variables) {
        KernelRegressionCategories kCat = new KernelRegressionCategories(v, kernelFunction, bandwidth,
                uniformDistributionApproximation);
        categoryRegression.put(v, kCat);
    }//w  w  w  .ja  v a2 s.  com

    //connect to db
    Table sqlTable = new Table(tableName.getNameForDatabase());
    SelectQuery select = new SelectQuery();
    for (VariableAttributes v : variables) {
        select.addColumn(sqlTable, v.getName().nameForDatabase());
    }
    select.addColumn(sqlTable, regressorVariable.getName().nameForDatabase());
    if (hasGroupVariable)
        select.addColumn(sqlTable, groupByVariable.getName().nameForDatabase());

    ResultSet rs = null;
    Statement stmt = null;

    try {
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery(select.toString());

        KernelRegressionCategories kernelRegressionCategories;
        Object itemResponse;
        Double score;
        Object tempGroup;
        String group;

        while (rs.next()) {
            //increment kernel regression objects
            //omit examinees with missing data
            score = rs.getDouble(regressorVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                for (VariableAttributes v : categoryRegression.keySet()) {
                    kernelRegressionCategories = categoryRegression.get(v);
                    itemResponse = rs.getObject(v.getName().nameForDatabase());
                    if (itemResponse != null)
                        kernelRegressionCategories.increment(score, itemResponse);
                }
            }
            updateProgress();
        }
    } catch (SQLException ex) {
        throw ex;
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
    }

    this.firePropertyChange("progress-ind-on", null, null);
}

From source file:com.bitnine.tadpole.graph.core.editor.extension.browserHandler.CypherFunctionService.java

/**
 * RurukiEye.js ?? ?   .//from   w  w w . j  a va  2  s . c  o m
 * 
 * @param nodeJsonString
 * @return
 */
protected String loadData(final String nodeJsonString) {
    ResultSet rs = null;
    java.sql.Connection javaConn = null;
    Statement statement = null;

    JsonObject jsonNode = JsonObject.readFrom(nodeJsonString);
    RunkiEyeGraph graph = new RunkiEyeGraph();

    try {

        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);

        String reqQuery = "match (n)-[r]->(p) where id(n) = '" + jsonNode.get("id").asString()
                + "' return n, r, p UNION match (n)-[r]->(p) where id(p) = '" + jsonNode.get("id").asString()
                + "' return n, r, p";
        if (logger.isDebugEnabled())
            logger.debug("Execute Math CQL : " + reqQuery);

        javaConn = client.getDataSource().getConnection();
        statement = javaConn.createStatement();

        rs = statement.executeQuery(reqQuery);
        ResultSetMetaData rsmt = rs.getMetaData();

        RurukiNode node = null;
        RurukiEdge rurukiEdge = null;
        Path path = null;

        while (rs.next()) {
            for (int columnIndex = 1; columnIndex <= rsmt.getColumnCount(); columnIndex++) {

                Object obj = rs.getObject(columnIndex);
                if (obj instanceof Vertex) {
                    node = new RurukiNode();
                    Vertex vertex = (Vertex) obj;
                    node.setId(vertex.getVertexId().getOid() + "." + vertex.getVertexId().getId());
                    node.setLabel(vertex.getLabel());
                    node.setProperties(vertex.getProperty().toMap());
                    node.setMetadata(new Metadata(0, 0, vertex));
                    graph.addVertex(node);
                } else if (obj instanceof Edge) {
                    rurukiEdge = new RurukiEdge();
                    Edge relation = (Edge) obj;
                    rurukiEdge.setId(relation.getEdgeId().getOid() + "." + relation.getEdgeId().getId());
                    rurukiEdge.setLabel(relation.getLabel());
                    rurukiEdge.setHeadId(
                            relation.getStartVertexId().getOid() + "." + relation.getStartVertexId().getId());
                    rurukiEdge.setTailId(
                            relation.getEndVertexid().getOid() + "." + relation.getEndVertexid().getId());
                    rurukiEdge.setProperties(relation.getProperty().toMap());
                    graph.addEdge(rurukiEdge);
                } else if (obj instanceof Path) {

                    path = (Path) obj;

                    for (Edge relation : path.edges()) {

                        rurukiEdge = new RurukiEdge();

                        rurukiEdge.setId(relation.getEdgeId().getOid() + "." + relation.getEdgeId().getId());
                        rurukiEdge.setLabel(relation.getLabel());
                        rurukiEdge.setHeadId(relation.getStartVertexId().getOid() + "."
                                + relation.getStartVertexId().getId());
                        rurukiEdge.setTailId(
                                relation.getEndVertexid().getOid() + "." + relation.getEndVertexid().getId());
                        rurukiEdge.setProperties(relation.getProperty().toMap());

                        graph.addEdge(rurukiEdge);

                    }

                    if (logger.isDebugEnabled())
                        logger.debug("path start " + path.start());
                    if (logger.isDebugEnabled())
                        logger.debug("path length " + String.valueOf(path.length()));
                    for (Vertex vertex : path.vertexs()) {
                        node = new RurukiNode();
                        node.setId(vertex.getVertexId().getOid() + "." + vertex.getVertexId().getId());
                        node.setLabel(vertex.getLabel());
                        node.setProperties(vertex.getProperty().toMap());
                        node.setMetadata(new Metadata(0, 0, vertex));

                        graph.addVertex(node);
                    }
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("Unknow Class " + obj.getClass().toString());
                }
            }
        }

        graph.calcInOutEdgeCount();

    } catch (Exception e) {
        logger.error(e);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (Exception e) {
        }
        try {
            if (rs != null)
                rs.close();
        } catch (Exception e) {
        }
        try {
            if (javaConn != null)
                javaConn.close();
        } catch (Exception e) {
        }

    }
    return graph.toJSONString();
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

private <T> List<T> commandToRecords(Class objClass, String command, HashMap<Method, String> fieldMapping,
        Object[] params) {//from   w  w w.jav  a  2s .  com
    PreparedStatement st = null;
    ResultSet rs = null;
    try {
        ArrayList<T> records = new ArrayList();
        st = conn.prepareStatement(command);
        setParams(st, params);
        rs = st.executeQuery();
        while (rs.next()) {
            T newObj = (T) objClass.newInstance();
            for (Method method : fieldMapping.keySet()) {
                try {
                    Object val = converter.convertType(rs.getObject((String) fieldMapping.get(method)), method);
                    if (val != null)
                        method.invoke(newObj, val);
                } catch (Exception ex) {
                    if (!method.isAnnotationPresent(Optional.class)) {
                        throw new DataQueryException(command, "Unable to map method:" + method.getName(), ex);
                    }
                }
            }
            records.add(newObj);
        }
        return records;
    } catch (Exception ex) {
        if (ex instanceof DataQueryException)
            throw (DataQueryException) ex;
        else
            throw new DataQueryException(command, null, ex);
    } finally {
        closeOnFinally(rs, st);
    }
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

private <T> List<T> commandToDbStruct(Class dbStructClazz, String command, HashMap<Field, String> fieldMapping,
        Object[] params) {/*w w w  .j av a 2s  . co m*/
    PreparedStatement st = null;
    ResultSet rs = null;
    try {
        ArrayList<T> records = new ArrayList();
        st = conn.prepareStatement(command);
        setParams(st, params);
        rs = st.executeQuery();
        while (rs.next()) {
            T newObj = (T) dbStructClazz.newInstance();
            for (Field field : fieldMapping.keySet()) {
                try {
                    Object val = converter.convertType(rs.getObject((String) fieldMapping.get(field)), field);
                    if (val != null)
                        field.set(newObj, val);
                } catch (Exception ex) {
                    throw new DataQueryException(command, "Unable to map field:" + field.getName(), ex);
                }
            }
            records.add(newObj);
        }
        return records;
    } catch (Exception ex) {
        if (ex instanceof DataQueryException)
            throw (DataQueryException) ex;
        else
            throw new DataQueryException(command, null, ex);
    } finally {
        closeOnFinally(rs, st);
    }
}

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

public String getRecordsAsJson(String sql, Object... params) {
    PreparedStatement st = null;//from   w ww  .  jav  a  2 s.co  m
    ResultSet rs = null;
    ResultSetMetaData rsMetaData = null;
    try {
        StringBuilder stringBuilder = null;
        stringBuilder = new StringBuilder("[");
        st = conn.prepareStatement(sql);
        setParams(st, params);
        rs = st.executeQuery();
        rsMetaData = rs.getMetaData();
        while (rs.next()) {
            stringBuilder.append("{");
            for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {
                String val;
                if (rs.getObject(i) == null) {
                    val = "";
                } else {
                    val = StringEscapeUtils.escapeJavaScript(rs.getObject(i).toString());
                }
                stringBuilder.append("\"").append(rsMetaData.getColumnName(i)).append("\":\"").append(val)
                        .append("\",");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            stringBuilder.append("},");
        }
        if (stringBuilder.length() > 1)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append("]");
        return stringBuilder.toString();
    } catch (Exception ex) {
        throw new NativeQueryException(sql, null, ex);
    } finally {
        closeOnFinally(rs, st);
    }

}

From source file:hoot.services.writers.review.ReviewPrepareDbWriter.java

protected Map<Long, Object> getParseableElementRecords(final long mapId, final ElementType elementType,
        final int limit, final int offset) throws InstantiationException, IllegalAccessException,
        ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
    Map<Long, Object> retMap = new LinkedHashMap<Long, Object>();
    final Element prototype = ElementFactory.getInstance().create(mapId, elementType, conn);
    String tableName = prototype.getElementTable().getTableName();
    String idFieldName = ColumnMetadata.getColumnMetadata(prototype.getElementIdField()).getName();

    String POSTGRESQL_DRIVER = "org.postgresql.Driver";
    Statement stmt = null;//  ww w.j  av  a2 s .c  o  m
    try {
        Class.forName(POSTGRESQL_DRIVER);

        stmt = conn.createStatement();

        String sql = "select * from " + tableName + "_" + mapId + " where " + "EXIST(tags, 'uuid') = TRUE "
                + " order by " + idFieldName + " limit " + limit + " offset " + offset;
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()) {

            if (elementType == ElementType.Node) {
                CurrentNodes nodes = new CurrentNodes();
                nodes.setId(rs.getLong("id"));

                nodes.setLatitude(rs.getInt("latitude"));
                nodes.setLongitude(rs.getInt("longitude"));
                nodes.setChangesetId(rs.getLong("changeset_id"));
                nodes.setVisible(rs.getBoolean("visible"));
                nodes.setTimestamp(rs.getTimestamp("timestamp"));
                nodes.setTile(rs.getLong("tile"));
                nodes.setVersion(rs.getLong("version"));
                nodes.setTags(rs.getObject("tags"));
                retMap.put(nodes.getId(), nodes);
            } else if (elementType == ElementType.Way) {
                CurrentWays ways = new CurrentWays();
                ways.setId(rs.getLong("id"));

                ways.setChangesetId(rs.getLong("changeset_id"));
                ways.setVisible(rs.getBoolean("visible"));
                ways.setTimestamp(rs.getTimestamp("timestamp"));
                ways.setVersion(rs.getLong("version"));
                ways.setTags(rs.getObject("tags"));
                retMap.put(ways.getId(), ways);
            } else if (elementType == ElementType.Relation) {
                CurrentRelations rel = new CurrentRelations();
                rel.setId(rs.getLong("id"));

                rel.setChangesetId(rs.getLong("changeset_id"));
                rel.setVisible(rs.getBoolean("visible"));
                rel.setTimestamp(rs.getTimestamp("timestamp"));
                rel.setVersion(rs.getLong("version"));
                rel.setTags(rs.getObject("tags"));
                retMap.put(rel.getId(), rel);
            }
        }
        rs.close();

    } catch (Exception e) {
        //throw new Exception("Error inserting node.");
    }

    finally {
        //finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {

        } // nothing we can do

    } //end try

    return retMap;
}