Example usage for java.sql Statement getResultSet

List of usage examples for java.sql Statement getResultSet

Introduction

In this page you can find the example usage for java.sql Statement getResultSet.

Prototype

ResultSet getResultSet() throws SQLException;

Source Link

Document

Retrieves the current result as a ResultSet object.

Usage

From source file:de.codecentric.multitool.db.DBUnitLibrary.java

/**
 * Liest einen Einzelwert aus einer Tabellenabfrage
 * //from w w  w . ja  va  2s.c o m
 * Beispiel: | ${value} = | Read Single Value From Table | ACSD_FULL |
 * MYTABLE | STATUS | id = 5 |
 */
public String readSingleValueFromTable(String dsName, String table, String column, String whereStatment)
        throws IllegalArgumentException, SQLException {
    Statement statement = null;
    ResultSet rs = null;
    try {
        statement = getConnection(dsName).createStatement();
        String sql = "SELECT " + column + " FROM " + table
                + (StringUtils.isNotEmpty(whereStatment) ? " WHERE " + whereStatment : "");
        statement.execute(sql);

        rs = statement.getResultSet();
        if (rs.next()) {
            if (rs.getObject(1) == null)
                return null;
            else
                return rs.getObject(1).toString();
        }
        throw new NoSuchElementException(sql);

    } finally {
        if (rs != null) {
            rs.close();
        }
        if (statement != null) {
            statement.close();
        }
    }
}

From source file:org.talend.dq.analysis.TableAnalysisSqlExecutor.java

protected List<Object[]> executeQuery(String catalogName, Connection connection, String queryStmt)
        throws SQLException {
    if (catalogName != null && needChangeCatalog(connection)) { // check whether null argument can be given
        changeCatalog(catalogName, connection);
    }// ww w . ja  v  a  2s.c om
    // create query statement
    Statement statement = connection.createStatement();
    // statement.setFetchSize(fetchSize);

    if (continueRun()) {
        statement.execute(queryStmt);
    }

    // get the results
    ResultSet resultSet = statement.getResultSet();
    if (resultSet == null) {
        String mess = Messages.getString("ColumnAnalysisSqlExecutor.NORESULTSETFORTHISSTATEMENT") + queryStmt;//$NON-NLS-1$
        log.warn(mess);
        return null;
    }
    ResultSetMetaData metaData = resultSet.getMetaData();
    int columnCount = metaData.getColumnCount();
    List<Object[]> myResultSet = new ArrayList<Object[]>();
    while (resultSet.next()) {
        Object[] result = new Object[columnCount];
        for (int i = 0; i < columnCount; i++) {
            result[i] = resultSet.getObject(i + 1);
        }
        myResultSet.add(result);
    }
    // -- release resources
    resultSet.close();
    statement.close();

    return myResultSet;
}

From source file:mom.trd.opentheso.bdd.helper.GpsHelper.java

private boolean isCoordoneesExist(HikariDataSource ds, String idC, String idTheso) {
    Connection conn;//from w  w w. j a  v  a  2 s  . com
    Statement stmt;
    ResultSet resultSet;
    boolean existe = false;
    try {
        // Get connection from pool
        conn = ds.getConnection();
        try {
            stmt = conn.createStatement();
            try {
                String query = "select id_concept from gps where " + "id_concept ='" + idC + "'"
                        + " and id_theso = '" + idTheso + "'";
                stmt.executeQuery(query);
                resultSet = stmt.getResultSet();
                if (resultSet.next()) {
                    existe = true;
                }
            } finally {
                stmt.close();
            }
        } finally {
            conn.close();
        }
    } catch (SQLException sqle) {
        // Log exception
        log.error("Error while Add coordonnes : " + idC, sqle);
    }
    return existe;
}

From source file:org.talend.dq.indicators.ColumnSetIndicatorEvaluator.java

/**
 * //from w  ww. j av  a 2  s. c  o  m
 * orgnize EList 'objectLs' by SQL.
 * 
 * @param sqlStatement
 * @param ok
 * @return
 * @throws SQLException
 */
private ReturnCode evaluateBySql(String sqlStatement, ReturnCode ok) throws SQLException {
    Statement statement = null;
    ResultSet resultSet = null;
    try {
        statement = createStatement();
        if (continueRun()) {
            if (log.isInfoEnabled()) {
                log.info("Executing query: " + sqlStatement); //$NON-NLS-1$
            }
            statement.execute(sqlStatement);
        }
        // get the results
        resultSet = statement.getResultSet();
        List<String> columnNames = getAnalyzedElementsName();

        if (resultSet == null) {
            String mess = Messages.getString("Evaluator.NoResultSet", sqlStatement); //$NON-NLS-1$
            log.warn(mess);
            ok.setReturnCode(mess, false);
            return ok;
        }
        EMap<Indicator, AnalyzedDataSet> indicToRowMap = analysis.getResults().getIndicToRowMap();
        indicToRowMap.clear();
        while (resultSet.next()) {
            // MOD yyi 2012-04-11 TDQ-4916:Add memory control for java analysis.
            if (!continueRun()) {
                break;
            }
            EList<Object> objectLs = new BasicEList<Object>();
            Iterator<String> it = columnNames.iterator();
            while (it.hasNext()) {
                Object obj = ResultSetUtils.getBigObject(resultSet, it.next());
                objectLs.add(obj);
            }
            if (objectLs.size() == 0) {
                continue;
            }
            handleObjects(objectLs, resultSet);
        }
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        closeConnection();
    }

    return ok;
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

private ResultSet getFirstResultSet(StatementScope scope, Statement stmt) throws SQLException {
    ResultSet rs = null;/* www. j  ava 2 s . c om*/
    boolean hasMoreResults = true;
    while (hasMoreResults) {
        rs = stmt.getResultSet();
        if (rs != null) {
            break;
        }
        hasMoreResults = moveToNextResultsIfPresent(scope, stmt);
    }
    return rs;
}

From source file:com.oracle.tutorial.jdbc.CoffeesTable.java

public void modifyPricesByPercentage(String coffeeName, float priceModifier, float maximumPrice)
        throws SQLException {
    con.setAutoCommit(false);//  w w w. j av a 2 s  . c  o  m

    Statement getPrice = null;
    Statement updatePrice = null;
    ResultSet rs = null;
    String query = "SELECT COF_NAME, PRICE FROM COFFEES " + "WHERE COF_NAME = '" + coffeeName + "'";

    try {
        Savepoint save1 = con.setSavepoint();
        getPrice = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        updatePrice = con.createStatement();

        if (!getPrice.execute(query)) {
            System.out.println("Could not find entry for coffee named " + coffeeName);
        } else {
            rs = getPrice.getResultSet();
            rs.first();
            float oldPrice = rs.getFloat("PRICE");
            float newPrice = oldPrice + (oldPrice * priceModifier);
            System.out.println("Old price of " + coffeeName + " is " + oldPrice);
            System.out.println("New price of " + coffeeName + " is " + newPrice);
            System.out.println("Performing update...");
            updatePrice.executeUpdate(
                    "UPDATE COFFEES SET PRICE = " + newPrice + " WHERE COF_NAME = '" + coffeeName + "'");
            System.out.println("\nCOFFEES table after update:");
            CoffeesTable.viewTable(con);
            if (newPrice > maximumPrice) {
                System.out.println("\nThe new price, " + newPrice + ", is greater than the maximum " + "price, "
                        + maximumPrice + ". Rolling back the transaction...");
                con.rollback(save1);
                System.out.println("\nCOFFEES table after rollback:");
                CoffeesTable.viewTable(con);
            }
            con.commit();
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (getPrice != null) {
            getPrice.close();
        }
        if (updatePrice != null) {
            updatePrice.close();
        }
        con.setAutoCommit(true);
    }
}

From source file:nl.b3p.viewer.util.databaseupdate.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in// w  w  w  .jav  a 2 s  .  c om
 *
 * @param conn - the connection to use for the script
 * @param reader - the source of the script
 * @throws SQLException if any SQL errors occur
 * @throws IOException if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                log.debug(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                log.debug(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        log.error("Error executing: " + command, e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        log.debug(name + "\t");
                    }
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            log.debug(value + "\t");
                        }
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        log.error("Error executing: " + command, e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        log.error("Error executing: " + command, e);
        throw e;
    } finally {
        if (!this.autoCommit) {
            conn.rollback();
        }
    }
}

From source file:org.huahinframework.manager.rest.service.HiveService.java

@Path("/execute")
@POST/*w w w  .ja  v  a 2 s.  c o  m*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaTypeUtils.MULTIPART_FORM_DATA)
public void execute(@Context HttpServletResponse response, InMultiPart inMP) throws IOException {
    OutputStreamWriter out = null;
    Map<String, String> status = new HashMap<String, String>();
    Map<String, Object> result = new HashMap<String, Object>();
    try {
        out = new OutputStreamWriter(response.getOutputStream());
        if (!inMP.hasNext()) {
            status.put(Response.STATUS, "Query is empty");
            out.write(new JSONObject(status).toString());
            out.flush();
            out.close();
            return;
        }

        JSONObject argument = createJSON(inMP.next().getInputStream());
        String query = argument.getString(JSON_QUERY);
        if (query == null || query.isEmpty()) {
            status.put(Response.STATUS, "Query is empty");
            out.write(new JSONObject(status).toString());
            out.flush();
            out.close();
            return;
        }

        Class.forName(driverName);
        Connection con = DriverManager.getConnection(String.format(connectionFormat, hiveserver), "", "");
        Statement stmt = con.createStatement();

        int queryNo = 1;
        String command = "";
        for (String oneCmd : query.split(";")) {
            if (StringUtils.endsWith(oneCmd, "")) {
                command += StringUtils.chop(oneCmd) + ";";
                continue;
            } else {
                command += oneCmd;
            }

            if (StringUtils.isBlank(command)) {
                continue;
            }

            boolean b = stmt.execute(command);
            if (b) {
                result.clear();
                result.put(JSON_QUERY, queryNo);

                ResultSet resultSet = stmt.getResultSet();
                while (resultSet.next()) {
                    JSONObject jsonObject = new JSONObject();
                    for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                        jsonObject.put(resultSet.getMetaData().getColumnName(i), resultSet.getString(i));
                    }
                    result.put(RESULT, jsonObject);

                    out.write(new JSONObject(result).toString());
                    out.flush();
                }

                if (result.size() == 1) {
                    status.put(Response.STATUS, "SCCESS");
                    result.put(RESULT, status);

                    JSONObject jsonObject = new JSONObject(result);
                    out.write(jsonObject.toString());
                    out.flush();
                }
            } else {
                result.clear();
                status.clear();

                result.put(JSON_QUERY, queryNo);

                status.put(Response.STATUS, "SCCESS");
                result.put(RESULT, status);

                JSONObject jsonObject = new JSONObject(result);
                out.write(jsonObject.toString());
                out.flush();
            }

            command = "";
            queryNo++;
        }

        con.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e);
        if (out != null) {
            status.put(Response.STATUS, e.getMessage());
            out.write(new JSONObject(status).toString());
            out.flush();
            out.close();
        }
    }
}

From source file:com.atolcd.alfresco.repo.patch.SchemaUpgradeScriptPatch.java

/**
 * Execute the given SQL statement, absorbing exceptions that we expect
 * during schema creation or upgrade./* ww  w  .  j a  va 2s.  com*/
 * 
 * @param fetchColumnName
 *            the name of the column value to return
 */
private Object executeStatement(Connection connection, String sql, String fetchColumnName, boolean optional,
        int line, File file) throws Exception {
    StringBuilder executedStatements = executedStatementsThreadLocal.get();
    if (executedStatements == null) {
        throw new IllegalArgumentException("The executedStatementsThreadLocal must be populated");
    }

    Statement stmt = connection.createStatement();
    Object ret = null;
    try {
        if (logger.isDebugEnabled()) {
            LogUtil.debug(logger, MSG_EXECUTING_STATEMENT, sql);
        }
        boolean haveResults = stmt.execute(sql);
        // Record the statement
        executedStatements.append(sql).append(";\n\n");
        if (haveResults && fetchColumnName != null) {
            ResultSet rs = stmt.getResultSet();
            if (rs.next()) {
                // Get the result value
                ret = rs.getObject(fetchColumnName);
            }
        }
    } catch (SQLException e) {
        if (optional) {
            // it was marked as optional, so we just ignore it
            LogUtil.debug(logger, MSG_OPTIONAL_STATEMENT_FAILED, sql, e.getMessage(), file.getAbsolutePath(),
                    line);
        } else {
            LogUtil.error(logger, ERR_STATEMENT_FAILED, sql, e.getMessage(), file.getAbsolutePath(), line);
            throw e;
        }
    } finally {
        try {
            stmt.close();
        } catch (Throwable e) {
        }
    }
    return ret;
}

From source file:org.hyperic.hq.plugin.sybase.SybaseServerDetector.java

private void setSpaceAvailServices(List services, Statement stmt) throws SQLException {
    ResultSet rs = null;/* w w w.j a va 2  s .  c om*/
    try {
        rs = stmt.executeQuery("select pagesize=@@maxpagesize");
        int pagesize = -1;
        if (rs.next())
            pagesize = rs.getInt("pagesize");
        else
            throw new SQLException();
        rs.close();
        List databases = getDatabases(stmt);
        for (int i = 0; i < databases.size(); i++) {
            String database = (String) databases.get(i);
            try {
                stmt.execute("use " + database);
                stmt.execute("sp_helpsegment");
                rs = stmt.getResultSet();
                while (rs.next()) {
                    String segment = rs.getString("name");
                    ServiceResource service = new ServiceResource();
                    service.setType(this, TYPE_STORAGE);
                    service.setServiceName(database + "." + segment);
                    ConfigResponse productConfig = new ConfigResponse();
                    productConfig.setValue(PROP_DATABASE, database);
                    productConfig.setValue(PROP_SEGMENT, segment);
                    productConfig.setValue(PROP_PAGESIZE, pagesize);
                    service.setProductConfig(productConfig);
                    service.setMeasurementConfig();
                    services.add(service);
                }
            } catch (SQLException e) {
                if (log.isDebugEnabled()) {
                    log.error("[setSpaceAvailServices] database '" + database + "' > " + e.getMessage(), e);
                }
            }
        }
    } finally {
        if (rs != null)
            rs.close();
        stmt.execute("use master");
    }
}