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:mom.trd.opentheso.bdd.helper.LanguageHelper.java

/**
 * Permet de retourner un ArrayList d'Objet Languages_iso639 de toute la table Language_iso639
 * c'est la liste des langues ISO639 / ou null si rien
 * //ww w.  j av  a 2 s.c  o m
 * @param ds le pool de connexion
 * @return Objet Class Thesaurus
 */
public ArrayList<Languages_iso639> getAllLanguages(HikariDataSource ds) {

    Connection conn;
    Statement stmt;
    ResultSet resultSet;
    ArrayList<Languages_iso639> language = new ArrayList<>();
    try {
        // Get connection from pool
        conn = ds.getConnection();
        try {
            stmt = conn.createStatement();
            try {
                String query1 = "select distinct * from languages_iso639 ORDER BY french_name";

                stmt.executeQuery(query1);
                resultSet = stmt.getResultSet();
                if (resultSet != null) {
                    language = new ArrayList<>();
                    while (resultSet.next()) {
                        Languages_iso639 languageTmp = new Languages_iso639();
                        languageTmp.setId_iso639_1(resultSet.getString("iso639_1"));
                        languageTmp.setId_iso639_2(resultSet.getString("iso639_2"));
                        languageTmp.setFrench_name(resultSet.getString("french_name"));
                        languageTmp.setEnglish_name(resultSet.getString("english_name"));
                        language.add(languageTmp);
                    }
                    resultSet.close();
                }

            } finally {
                stmt.close();
            }
        } finally {
            conn.close();
        }
    } catch (SQLException sqle) {
        // Log exception
        log.error("Error while adding element : " + language, sqle);
    }
    return language;
}

From source file:org.verdictdb.connection.JdbcConnection.java

public DbmsQueryResult executeSingle(String sql) throws VerdictDBDbmsException {
    log.debug("Issues the following query to DBMS: " + sql);

    try {/*from  w  w  w  .j  a  v  a2  s  .  co m*/
        Statement stmt = conn.createStatement();
        setRunningStatement(stmt);
        JdbcQueryResult jrs = null;
        boolean doesResultExist = stmt.execute(sql);
        if (doesResultExist) {
            ResultSet rs = stmt.getResultSet();
            jrs = new JdbcQueryResult(rs);
            rs.close();
        } else {
            jrs = null;
        }
        setRunningStatement(null);
        stmt.close();
        return jrs;
    } catch (SQLException e) {
        if (isAborting) {
            return null;
        } else {
            String msg = "Issued the following query: " + sql + "\n" + e.getMessage();
            throw new VerdictDBDbmsException(msg);
        }
    }
}

From source file:it.unibas.spicygui.controllo.provider.intermediatezone.MyEditProviderConst.java

public String verificaDati() throws DAOException, SQLException {
    String type = null;//from  w  ww.  ja  v  a2 s  . co m
    if (this.dialog.getJRadioButtonFunction().isSelected()) {
        if (this.dialog.getJComboBoxFunction().getSelectedItem().toString().equalsIgnoreCase("newId()")) {
            String sequence = this.dialog.getTextSequenceName().getText().trim();
            if (SpicyEngineConstants.GET_ID_FROM_DB.get(sequence) != null)
                SpicyEngineConstants.TEMP_DB_PROPERTIES = SpicyEngineConstants.GET_ID_FROM_DB.get(sequence);

            caratteristiche.setCostante(this.dialog.getJComboBoxFunction().getSelectedItem() + "_" + sequence);

            if (this.dialog.getJRadioButtonConstant().isSelected()) {
                SpicyEngineConstants.OFFSET_MAPPING.put(sequence, this.dialog.getOffsetText().getText().trim());
                type = "constant";
            } else if (this.dialog.getJRadioButtonDatabase().isSelected()) {
                if (SpicyEngineConstants.TEMP_DB_PROPERTIES != null) {
                    Connection connection = connectToDb();
                    Statement statement = connection.createStatement();
                    if (SpicyEngineConstants.TEMP_DB_PROPERTIES.getFunction().equalsIgnoreCase("max")) {
                        statement.execute("SELECT MAX(\"" + SpicyEngineConstants.TEMP_DB_PROPERTIES.getColumn()
                                + "\") FROM \"" + SpicyEngineConstants.TEMP_DB_PROPERTIES.getTable() + "\";");
                    }
                    ResultSet rs = statement.getResultSet();
                    if (rs.next()) {
                        SpicyEngineConstants.OFFSET = String.valueOf(rs.getInt(1));
                    } else {
                        SpicyEngineConstants.OFFSET = "0";
                    }
                    SpicyEngineConstants.OFFSET_MAPPING.put(sequence, SpicyEngineConstants.OFFSET);
                    SpicyEngineConstants.GET_ID_FROM_DB.put(sequence, SpicyEngineConstants.TEMP_DB_PROPERTIES);
                    SpicyEngineConstants.TEMP_DB_PROPERTIES = null;
                    type = "getId()";
                } else {
                    if (dialog.getReturnStatus() == ConstantDialog.RET_OK) {
                        JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
                                "Please setup the database configuration!", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                if (dialog.getReturnStatus() == ConstantDialog.RET_OK) {
                    JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
                            "Please select offset source input!", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else if (this.dialog.getJComboBoxFunction().getSelectedItem().toString().equalsIgnoreCase("date()")) {
            type = "date";
            caratteristiche.setCostante(this.dialog.getJComboBoxFunction().getSelectedItem());
        } else {
            type = "datetime";
            caratteristiche.setCostante(this.dialog.getJComboBoxFunction().getSelectedItem());
        }
    }
    if (this.dialog.getJRadioButtonNumber().isSelected()) {
        type = "number";
        Double.parseDouble((String) caratteristiche.getCostante());
    }
    if (this.dialog.getJRadioButtonString().isSelected()) {
        type = "string";
        String valoreCostante = (String) caratteristiche.getCostante();
        caratteristiche.setCostante(Utility.sostituisciVirgolette(valoreCostante));
    }
    caratteristiche.setType(type);
    return type;
}

From source file:herddb.cli.HerdDBCLI.java

private static ExecuteStatementResult reallyExecuteStatement(final Statement statement, boolean resultSet,
        boolean verbose, boolean getResults, boolean prettyPrint) throws SQLException {

    if (resultSet) {
        try (ResultSet rs = statement.getResultSet()) {
            List<Map<String, Object>> results = new ArrayList<>();
            TextTableBuilder tb = new TextTableBuilder();

            ResultSetMetaData md = rs.getMetaData();
            List<String> columns = new ArrayList<>();
            int ccount = md.getColumnCount();
            for (int i = 1; i <= ccount; i++) {
                columns.add(md.getColumnName(i));
            }//from   w  w w .  j a v  a 2 s. c o m

            if (!getResults) {
                if (prettyPrint) {
                    tb.addIntestation(columns);
                } else {
                    System.out.println(columns.stream().collect(Collectors.joining(";")));
                }
            }

            while (rs.next()) {
                List<String> values = new ArrayList<>();
                for (int i = 1; i <= ccount; i++) {
                    String value = rs.getString(i);
                    if (value == null) {
                        value = "<NULL>";
                    }
                    values.add(value);
                }

                if (getResults) {
                    Map<String, Object> row = new LinkedHashMap<>(); // Preserving order
                    int i = 0;
                    for (String col : columns) {
                        row.put(col, values.get(i++));
                    }
                    results.add(row);
                } else {
                    if (prettyPrint) {
                        tb.addRow(values);
                    } else {
                        System.out.println(values.stream().collect(Collectors.joining(";")));
                    }
                }
            }

            if (getResults) {
                return new ExecuteStatementResult(results);
            }
            if (prettyPrint) {
                System.out.println("\n" + tb.toString());
            }
            return null;
        }
    } else {
        int updateCount = statement.getUpdateCount();
        if (verbose) {
            System.out.println("UPDATE COUNT: " + updateCount);
        }
        return new ExecuteStatementResult(updateCount >= 0 ? updateCount : 0);
    }
}

From source file:org.blocks4j.reconf.client.setup.DatabaseManager.java

private boolean tableExists() throws Exception {
    Connection conn = null;/*from w  w w  .  j  av  a  2  s .c o m*/
    Statement stmt = null;
    try {
        conn = getConnection();
        stmt = conn.createStatement();
        stmt.execute("SELECT 1                                 " + "FROM   INFORMATION_SCHEMA.TABLES         "
                + "WHERE  TABLE_CATALOG = 'PUBLIC'          " + "AND    TABLE_SCHEMA = 'PUBLIC'           "
                + "AND    TABLE_NAME='CLS_METHOD_PROP_VALUE'");
        return stmt.getResultSet().next();

    } finally {
        close(stmt);
        close(conn);
    }
}

From source file:com.diversityarrays.dal.server.SqlWorker.java

public Response createResponse(SqlResponseType rtype, String sql, String metaTagName,
        Transformer<Boolean, DalResponseBuilder> builderFactory) {

    if (metaTagName == null && !rtype.isText()) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        new IllegalArgumentException("No metaTagName supplied for rtype=" + rtype).printStackTrace(pw);
        pw.close();/*from www  .j  av a 2s .  c  om*/
        return new Response(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, sw.toString());
    }

    Response result;

    Statement stmt = null;
    ResultSet rs = null;
    try {

        Connection conn = getConnection();

        stmt = conn.createStatement();

        if (rtype.isText()) {
            StringBuilder sb = new StringBuilder("<html><body>");

            sb.append("<code>").append(DbUtil.htmlEscape(sql)).append("</code><hr/>");

            boolean hasResultSet = stmt.execute(sql);

            if (hasResultSet) {
                rs = stmt.getResultSet();
                DalServerUtil.appendResultSetRowsAsTable("No data rows returned", rs, sb);
                sb.append("</body></html>");
            } else {
                int n = stmt.getUpdateCount();
                sb.append("Update count=").append(n);
            }

            result = new Response(Response.Status.OK, NanoHTTPD.MIME_HTML, sb.toString());
        } else {
            if (verbose) {
                System.err.println("sql: " + sql);
            }

            DalResponseBuilder builder = builderFactory == null ? DalServerUtil.createBuilder(rtype.isJson())
                    : builderFactory.transform(rtype.isJson());
            boolean hasResultSet = stmt.execute(sql);

            if (hasResultSet) {
                rs = stmt.getResultSet();
                DalServerUtil.appendResultSetRows(rs, builder, metaTagName);
                result = builder.build(Response.Status.OK);
            } else {
                int n = stmt.getUpdateCount();
                builder.startTag(DALClient.TAG_INFO).attribute(DALClient.ATTR_MESSAGE, "Update Count=" + n)
                        .endTag();
                result = builder.build(Response.Status.OK);
            }
        }
    } catch (SQLException e) {
        // Once for the log
        e.printStackTrace();

        if (SqlResponseType.TEXT == rtype) {
            // Browser request gets it all as text
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.close();
            result = new Response(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, sw.toString());
        } else {
            // DAL client gets just the message part
            result = DalServerUtil.buildErrorResponse(SqlResponseType.JSON == rtype, e.getMessage());
        }
    } catch (DalDbException e) {
        result = DalServerUtil.buildErrorResponse(SqlResponseType.JSON == rtype, e.getMessage());
    } finally {
        SqlUtil.closeSandRS(stmt, rs);
    }

    return result;
}

From source file:org.apache.hadoop.chukwa.extraction.engine.datasource.database.DatabaseDS.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE", justification = "Dynamic based upon tables in the database")
public SearchResult search(SearchResult result, String cluster, String dataSource, long t0, long t1,
        String filter, Token token) throws DataSourceException {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
    String timeField = null;/*from   ww w .j ava  2s . co  m*/
    TreeMap<Long, List<Record>> records = result.getRecords();

    if (cluster == null) {
        cluster = "demo";
    }

    if (dataSource.equalsIgnoreCase("MRJob")) {
        timeField = "LAUNCH_TIME";
    } else if (dataSource.equalsIgnoreCase("HodJob")) {
        timeField = "StartTime";
    } else {
        timeField = "timestamp";
    }
    String startS = formatter.format(t0);
    String endS = formatter.format(t1);
    Statement stmt = null;
    ResultSet rs = null;
    try {
        String dateclause = timeField + " >= '" + startS + "' and " + timeField + " <= '" + endS + "'";

        // ClusterConfig cc = new ClusterConfig();
        String jdbc = ""; // cc.getURL(cluster);

        Connection conn = org.apache.hadoop.chukwa.util.DriverManagerUtil.getConnection(jdbc);

        stmt = conn.createStatement();
        String query = "";
        query = "select * from " + dataSource + " where " + dateclause + ";";
        rs = stmt.executeQuery(query);
        if (stmt.execute(query)) {
            rs = stmt.getResultSet();
            ResultSetMetaData rmeta = rs.getMetaData();
            int col = rmeta.getColumnCount();
            while (rs.next()) {
                ChukwaRecord event = new ChukwaRecord();
                StringBuilder cell = new StringBuilder();
                ;
                long timestamp = 0;

                for (int i = 1; i < col; i++) {
                    String value = rs.getString(i);
                    if (value != null) {
                        cell.append(" ");
                        cell.append(rmeta.getColumnName(i));
                        cell.append(":");
                        cell.append(value);
                    }
                    if (rmeta.getColumnName(i).equals(timeField)) {
                        timestamp = rs.getLong(i);
                        event.setTime(timestamp);
                    }
                }
                boolean isValid = false;
                if (filter == null || filter.equals("")) {
                    isValid = true;
                } else if (cell.indexOf(filter) > 0) {
                    isValid = true;
                }
                if (!isValid) {
                    continue;
                }

                event.add(Record.bodyField, cell.toString());
                event.add(Record.sourceField, cluster + "." + dataSource);
                if (records.containsKey(timestamp)) {
                    records.get(timestamp).add(event);
                } else {
                    List<Record> list = new LinkedList<Record>();
                    list.add(event);
                    records.put(event.getTime(), list);
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw new DataSourceException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) {
                log.debug(ExceptionUtil.getStackTrace(sqlEx));
            }
            rs = null;
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException sqlEx) {
                log.debug(ExceptionUtil.getStackTrace(sqlEx));
            }
            stmt = null;
        }
    }
    return result;
}

From source file:wikipedia.sql.Links.java

/** @param skip_titles list of titles to be skipped */
public static String[] getTitleToByIDFrom(SessionHolder session, String title_from, int pl_from,
        PageNamespace namespace,/*  ww  w .  j a  v  a  2  s  . com*/
        //List<String> skip_titles, 
        Map<String, Set<String>> m_out, Map<String, Set<String>> m_in) {
    if (0 == pl_from) {
        return NULL_STRING_ARRAY;
    }

    Statement s = null;
    ResultSet rs = null;
    List<String> titles = new ArrayList<String>();

    sb.setLength(0);
    sb.append("SELECT pl_title FROM pagelinks WHERE pl_from=");
    sb.append(pl_from < 0 ? -pl_from : pl_from);
    sb.append(" AND pl_namespace=");
    sb.append(namespace.toInt());

    int size, i = 0;
    //String str_sql = null;
    try {
        s = session.connect.conn.createStatement();
        //str_sql = "SELECT pl_title FROM pagelinks WHERE " + sb.toString() + " AND pl_namespace="+namespace;

        //System.out.print("GetTitleToByIDFrom 1 sql="+sb.toString());
        s.executeQuery(sb.toString());
        //GetTitleToByIDFromQuery(rs, s, sb);
        //System.out.println(" OK.");

        rs = s.getResultSet();

        while (rs.next()) {
            Encodings e = session.connect.enc;
            String db_str = Encodings.bytesTo(rs.getBytes("pl_title"), e.GetDBEnc());
            String utf8_str = e.EncodeFromDB(db_str);

            //if(!session.skipTitle(utf8_str)) {
            //if(!skip_titles.contains(utf8_str)) {
            titles.add(utf8_str);
            //titles.add(connect.enc.EncodeFromDB(rs.getString("pl_title")));
            //}
            addTitlesToMaps(title_from, utf8_str, m_out, m_in);
            //}

            /*if(max_pl_title_len < utf8_str.length()) {
            max_pl_title_len = utf8_str.length();
            System.out.println("GetTitleToByIDFrom max_pl_title_len="+max_pl_title_len);
            }*/
        }
        /*if(max_titles_len < titles.size()) {
        max_titles_len = titles.size();
        System.out.println("GetTitleToByIDFrom max_titles_len="+max_titles_len);
        }*/

    } catch (SQLException ex) {
        System.err.println("SQLException (Links.java GetTitleToByIDFrom 1): sql='" + sb.toString() + "' "
                + ex.getMessage());
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) {
            }
            rs = null;
        }
        if (s != null) {
            try {
                s.close();
            } catch (SQLException sqlEx) {
            }
            s = null;
        }
    }
    return (String[]) titles.toArray(NULL_STRING_ARRAY);
}

From source file:reconf.client.setup.DatabaseManager.java

private boolean tableExists() throws Exception {
    Connection conn = null;//  ww  w .  j a v a 2 s  .  c o m
    Statement stmt = null;
    try {
        conn = getConnection();
        stmt = conn.createStatement();
        stmt.execute("SELECT 1                                     "
                + "FROM   INFORMATION_SCHEMA.TABLES             "
                + "WHERE  TABLE_CATALOG = 'PUBLIC'              "
                + "AND    TABLE_SCHEMA = 'PUBLIC'               "
                + "AND    TABLE_NAME='CLS_METHOD_PROP_VALUE_V2' ");
        return stmt.getResultSet().next();

    } finally {
        close(stmt);
        close(conn);
    }
}

From source file:capture.MySQLDatabase.java

public boolean loadTemporaryValue() {
    Connection con = this.getConnection();
    Statement stmt;
    ResultSet rs;//from www .j a va  2  s. c  o  m
    boolean result = false;
    try {
        stmt = con.createStatement();

        //Add status values into memory
        stmt.executeQuery("SELECT status_id, name FROM status");
        rs = stmt.getResultSet();
        while (rs.next()) {
            ConfigManager.getInstance().addConfigOption("status-" + rs.getString(2).toLowerCase(),
                    rs.getString(1));
        }

        //Add client program values into memory
        stmt.executeQuery("SELECT clientprogram_id, name FROM clientprogram");
        rs = stmt.getResultSet();
        while (rs.next()) {
            ConfigManager.getInstance().addConfigOption("clientprogram-" + rs.getString(2).toLowerCase(),
                    rs.getString(1));
        }
        stmt.close();
        con.close();
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}