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:org.alinous.plugin.mysql.MySQLDataSource.java

private List<Record> executeSelectSQL(Object connectionHandle, String sql) throws DataSourceException {
    Connection con = (Connection) connectionHandle;
    Statement stmt = null;
    List<Record> retList = new LinkedList<Record>();

    try {//from w ww.j a  va  2  s  .  c  o  m
        stmt = con.createStatement();
        stmt.execute(sql);

        ResultSet rs = stmt.getResultSet();
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()) {
            int cnt = metaData.getColumnCount();
            Record rec = new Record();
            for (int i = 0; i < cnt; i++) {
                String colName = metaData.getColumnName(i + 1);

                String labelName = metaData.getColumnLabel(i + 1);
                if (labelName != null && !labelName.equals("")) {
                    colName = labelName;
                }

                String value = rs.getString(i + 1);

                int colType = metaData.getColumnType(i + 1);
                rec.addFieldValue(colName, value, colType);
            }

            retList.add(rec);
        }

    } catch (SQLException e) {
        throw new DataSourceException(e);
    } finally {
        try {
            stmt.close();
        } catch (SQLException ignore) {
        }
    }

    return retList;
}

From source file:it.unibas.spicy.persistence.DAOMappingTaskLines.java

private void getOffSetFromDB(Element elementGetId, String sequence) throws DAOException, SQLException {
    Element driverElement = elementGetId.getChild("driver");
    Element uriElement = elementGetId.getChild("uri");
    Element schemaNameElement = elementGetId.getChild("schema");
    Element loginElement = elementGetId.getChild("login");
    Element passwordElement = elementGetId.getChild("password");
    Element tableElement = elementGetId.getChild("table");
    Element columnElement = elementGetId.getChild("column");
    Element functionElement = elementGetId.getChild("function");

    String schema = "";
    if (schemaNameElement != null) {
        schema = schemaNameElement.getTextTrim();
    }/*from  w ww . ja va  2 s.  c  o m*/

    GetIdFromDb newIdFromDb = new GetIdFromDb(driverElement.getTextTrim(), uriElement.getTextTrim(), schema,
            loginElement.getTextTrim(), passwordElement.getTextTrim(), tableElement.getTextTrim(),
            columnElement.getTextTrim(), functionElement.getTextTrim());
    SpicyEngineConstants.GET_ID_FROM_DB.put(sequence, newIdFromDb);

    AccessConfiguration accessConfiguration = new AccessConfiguration();
    accessConfiguration.setDriver(newIdFromDb.getDriver());
    accessConfiguration.setUri(newIdFromDb.getUri());
    if (schemaNameElement != null) {
        accessConfiguration.setSchemaName(newIdFromDb.getSchema());
    }
    accessConfiguration.setLogin(newIdFromDb.getLogin());
    accessConfiguration.setPassword(newIdFromDb.getPassword());
    IConnectionFactory connectionFactory = new SimpleDbConnectionFactory();
    Connection connection = connectionFactory.getConnection(accessConfiguration);
    Statement statement = connection.createStatement();

    if (newIdFromDb.getFunction().equalsIgnoreCase("max")) {
        statement.execute(
                "SELECT MAX(\"" + newIdFromDb.getColumn() + "\") FROM \"" + newIdFromDb.getTable() + "\";");
        ResultSet rs = statement.getResultSet();
        if (rs.next()) {
            SpicyEngineConstants.OFFSET_MAPPING.put(sequence, String.valueOf(rs.getInt(1)));
        } else {
            SpicyEngineConstants.OFFSET_MAPPING.put(sequence, "0");
        }
    }
}

From source file:architecture.common.spring.jdbc.core.ExtendedJdbcTemplate.java

protected Object runScript(Connection conn, boolean stopOnError, Reader reader)
        throws SQLException, IOException {

    StringBuffer command = null;/*ww  w  . j  ava2  s  .co  m*/
    List<Object> list = new ArrayList<Object>();
    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("--")) {
                if (logger.isDebugEnabled())
                    logger.debug(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (trimmedLine.endsWith(";")) {
                command.append(line.substring(0, line.lastIndexOf(";")));
                command.append(" ");

                Statement statement = conn.createStatement();
                if (logger.isDebugEnabled()) {
                    logger.debug("Executing SQL script command [" + command + "]");
                }

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        if (logger.isDebugEnabled())
                            logger.error("Error executing: " + command, e);
                        throw e;
                    }
                }
                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    RowMapperResultSetExtractor<Map<String, Object>> rse = new RowMapperResultSetExtractor<Map<String, Object>>(
                            getColumnMapRowMapper());
                    List<Map<String, Object>> rows = rse.extractData(rs);
                    list.add(rows);
                }
                command = null;
            } else {
                command.append(line);
                command.append(" ");
            }
        }

        return list;
    } catch (SQLException e) {
        logger.error("Error executing: " + command, e);
        throw e;
    } catch (IOException e) {
        logger.error("Error executing: " + command, e);
        throw e;
    }
}

From source file:org.dllearner.scripts.evaluation.EnrichmentEvaluation.java

public String printHTMLTable() throws SQLException {
    StringBuffer sb = new StringBuffer();
    Statement s = conn.createStatement();
    s.executeQuery("SELECT * FROM evaluation");
    java.sql.ResultSet rs = s.getResultSet();

    ResultSetMetaData md = rs.getMetaData();
    int count = md.getColumnCount();
    sb.append("<table border=1>");
    sb.append("<tr>");
    for (int i = 1; i <= count; i++) {
        sb.append("<th>");
        sb.append(md.getColumnLabel(i));
        sb.append("</th>");
    }/*from  w  w w  .  j  a v  a  2  s.  c om*/
    sb.append("</tr>");
    while (rs.next()) {
        sb.append("<tr>");
        for (int i = 1; i <= count; i++) {
            sb.append("<td>");
            sb.append(rs.getString(i));
            sb.append("</td>");
        }
        sb.append("</tr>");
    }
    sb.append("</table>");
    rs.close();
    s.close();
    return sb.toString();
}

From source file:vitro.vspEngine.service.persistence.DBCommons.java

synchronized public void insertUser(String ploginName, String pemailAddress, String ppasswd, String proleName) {
    java.sql.Connection conn = null;
    try {/*from   ww  w  . j a  v a  2 s . c om*/
        String echomessage = "";
        Class.forName(jdbcdriverClassName).newInstance();
        conn = DriverManager.getConnection(connString, usrStr, pwdStr);
        if (!conn.isClosed()) {
            Statement stmt = null;
            ResultSet rs = null;
            try {
                stmt = conn.createStatement();
                if (stmt.execute(
                        "SELECT * FROM `" + dbSchemaStr + "`.`users` where `login`=\'" + ploginName + "\'")) {
                    rs = stmt.getResultSet();
                }
                if (rs == null) {
                    int refRoleId = -1;
                    int refUserId = -1;

                    if (stmt.execute("START TRANSACTION")) {
                        rs = stmt.getResultSet(); // TODO: this is not needed here...
                    }
                    if (stmt.execute("INSERT INTO `" + dbSchemaStr
                            + "`.`users` (`login`, `email`, `passwd`, `lastadvtimestamp`, `disabled`) VALUES (\'"
                            + ploginName + "\',\'" + pemailAddress + "\',\'" + ppasswd + "\',0,0)")) {
                        rs = stmt.getResultSet(); // TODO: this is not needed here...
                    }
                    if (stmt.execute("SELECT `idusers` from `" + dbSchemaStr + "`.`users` where `login`= \'"
                            + ploginName + "\'")) {
                        rs = stmt.getResultSet();
                        refUserId = rs.getInt("idusers");
                    }
                    if (stmt.execute("SELECT `idroles` from `" + dbSchemaStr + "`.`roles` where `role_name`= \'"
                            + proleName + "\'")) {
                        rs = stmt.getResultSet();
                        refRoleId = rs.getInt("idroles");
                    }
                    if (stmt.execute(
                            "INSERT INTO `" + dbSchemaStr + "`.`userinrolesmr` (`idrole`, `iduser`) VALUES (\'"
                                    + refRoleId + "\',\'" + refUserId + "\')")) {
                        rs = stmt.getResultSet(); // TODO: this is not needed here...
                    }
                    if (stmt.execute("COMMIT")) {
                        rs = stmt.getResultSet(); // TODO: this is not needed here...
                    }

                } else
                    System.err.println("The inserted value already exists");

            } catch (SQLException ex) {
                // handle any errors
                System.err.println("SQLException3: " + ex.getMessage());
                System.err.println("SQLState3: " + ex.getSQLState());
                System.err.println("VendorError3: " + ex.getErrorCode());
            } finally {
                // it is a good idea to release
                // resources in a finally{} block
                // in reverse-order of their creation
                // if they are no-longer needed
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException sqlEx) {
                    } // ignore
                    rs = null;
                }
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException sqlEx) {
                    } // ignore
                    stmt = null;
                }
            }
        } else {
            echomessage = "Error accessing DB server...";
        }
        // DEBUG
        //System.out.println(echomessage);
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
        }
    }
}

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

/**
 * Permet de crer un nouveau Thsaurus. Retourne l'identifiant du thsaurus
 * ou null//from   w w w.j  a  va 2  s  . co m
 *
 * @param ds le pool de connexion
 * @param thesaurus
 * @param urlSite
 * @param isArkActive
 * @return String Id du thsaurus rajout
 */
public String addThesaurus(HikariDataSource ds, Thesaurus thesaurus, String urlSite, boolean isArkActive) {

    String idThesaurus = null;//"TH";//"ark:/66666/srvq9a5Ll41sk";
    Connection conn;
    Statement stmt;
    ResultSet resultSet;

    try {
        // Get connection from pool
        conn = ds.getConnection();
        try {
            stmt = conn.createStatement();
            try {
                String query = "select max(id) from thesaurus";
                stmt.executeQuery(query);
                resultSet = stmt.getResultSet();
                resultSet.next();
                int idNumeriqueThesaurus = resultSet.getInt(1);
                idThesaurus = "" + ++idNumeriqueThesaurus;

                /**
                 * rcupration du code Ark via WebServices
                 *
                 */
                String idArk = "";

                if (isArkActive) {
                    ArrayList<DcElement> dcElementsList = new ArrayList<>();
                    Ark_Client ark_Client = new Ark_Client();
                    idArk = ark_Client.getArkId(new FileUtilities().getDate(), urlSite + "?idt=" + idThesaurus,
                            "", "", dcElementsList, "pcrt"); // pcrt : p= pactols, crt=code DCMI pour collection
                }

                query = "Insert into thesaurus (id_thesaurus," + " id_ark, created, modified)" + " values ("
                        + "'" + idThesaurus + "'" + ",'" + idArk + "'" + "," + "current_date,"
                        + "current_date)";

                stmt.executeUpdate(query);
                thesaurus.setId_thesaurus(idThesaurus);
                /*   if(thesaurus.getTitle().isEmpty()){
                thesaurus.setTitle("Theso_" + idThesaurus);
                   }
                   addThesaurusTraduction(ds, thesaurus);*/

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

From source file:org.alinous.plugin.derby.DerbyDataSource.java

private List<Record> executeSelectSQL(Object connectionHandle, String sql, LimitOffsetClause limit,
        PostContext context, VariableRepository provider, AdjustWhere adjWhere, TypeHelper helper)
        throws DataSourceException, ExecutionException {
    Connection con = (Connection) connectionHandle;
    Statement stmt = null;
    List<Record> retList = new LinkedList<Record>();

    try {/*from  w ww. ja v  a 2  s  . c o m*/
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        stmt.execute(sql);

        ResultSet rs = stmt.getResultSet();

        ResultSetMetaData metaData = rs.getMetaData();

        if (limit != null && limit.isReady(context, provider, adjWhere)) {
            fetchWithOffset(rs, metaData, retList, limit, context, provider, adjWhere, helper);
        } else {
            while (rs.next()) {
                int cnt = metaData.getColumnCount();
                Record rec = new Record();
                for (int i = 0; i < cnt; i++) {
                    String colName = metaData.getColumnName(i + 1).toUpperCase();
                    String value = rs.getString(i + 1);

                    int colType = metaData.getColumnType(i + 1);
                    rec.addFieldValue(colName, value, colType);
                }

                retList.add(rec);
            }
        }

    } catch (SQLException e) {
        throw new DataSourceException(e);
    } finally {
        try {
            stmt.close();
        } catch (SQLException ignore) {
        }
    }

    return retList;
}

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

/**
 * Cette fonction permet de rcuprer l'identifiant Ark
 * sinon renvoie un une chaine vide/*from  w  w  w . j  a  va2  s. c  o  m*/
 *
 * @param ds
 * @param idThesaurus
 * @return String idArk
 */
public String getIdArkOfThesaurus(HikariDataSource ds, String idThesaurus) {

    Connection conn;
    Statement stmt;
    ResultSet resultSet;
    String ark = "";
    try {
        conn = ds.getConnection();
        try {
            stmt = conn.createStatement();
            try {
                String query = "select id_ark from thesaurus where" + " id_thesaurus = '" + idThesaurus + "'";
                stmt.executeQuery(query);
                resultSet = stmt.getResultSet();

                if (resultSet.next()) {
                    ark = resultSet.getString("id_ark");
                }

            } finally {
                stmt.close();
            }
        } finally {
            conn.close();
        }
    } catch (SQLException sqle) {
        // Log exception
        log.error("Error while getting idArk of Thesaurus : " + idThesaurus, sqle);
    }
    return ark;
}

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

/**
 * Cette fonction permet de savoir si le thesaurus existe ou non
 *
 * @param conn// w w w.  j a  v a  2s .  c o m
 * @param idThesaurus
 * @return boolean
 */
public boolean isThesaurusExiste(Connection conn, String idThesaurus) {

    Statement stmt;
    ResultSet resultSet;
    boolean existe = false;

    try {
        try {
            stmt = conn.createStatement();
            try {
                String query = "select id_thesaurus from thesaurus where " + " id_thesaurus = '" + idThesaurus
                        + "'";
                stmt.executeQuery(query);
                resultSet = stmt.getResultSet();
                if (resultSet.next()) {
                    existe = resultSet.getRow() != 0;
                }

            } finally {
                stmt.close();
            }
        } finally {
        }
    } catch (SQLException sqle) {
        // Log exception
        log.error("Error while asking if thesaurus exist : " + idThesaurus, sqle);
    }
    return existe;
}

From source file:migration.ProjektMigration.java

/**
 * Creates the interessen./*from   w  w w  .j  a  v a2  s . c om*/
 */
public void createInteressen() {

    String load_sql;
    Statement load_stmt;
    ResultSet load_rs;

    String store_sql;
    PreparedStatement store_prepstmt;
    final ResultSet store_rs;

    try {

        load_sql = "SELECT Besteller, Titelnummer, Interesse FROM Interessentabelle";
        load_stmt = this.leg_con.createStatement();

        store_sql = "INSERT INTO Interesse (besteller_bestellerId, interesse, journal_id) values (?, ?, ?)";
        store_prepstmt = this.tgt_con.prepareStatement(store_sql); // evtl.
        // brauchen
        // wir
        // was
        // in
        // Richtung:
        // Statement.RETURN_GENERATED_KEYS

        // logger.info("Lese von Interessen");
        load_stmt.execute(load_sql);
        load_rs = load_stmt.getResultSet();

        // logger.info("Schreibe nach Interessen");
        while (load_rs.next()) {
            final int titelnummer = load_rs.getInt("Titelnummer");
            final int journalID = this.help.getIdFromIntArray(this.help.getJournals(), titelnummer);
            // System.out.println("Titelnummer: " + titelnummer +
            // " JournalID " + journalID);
            if ((titelnummer > 0) && (journalID > 0)) {
                store_prepstmt.setLong(1,
                        this.help.getIdFromStringArray(this.bestellers, load_rs.getString("Besteller")));
                store_prepstmt.setString(2, load_rs.getString("Interesse"));
                store_prepstmt.setLong(3, journalID);// help.getIdFromIntArray(help.getJournals(),
                // load_rs.getInt("Titelnummer")));
                store_prepstmt.executeUpdate();
            }
        }

    } catch (final SQLException e) {
        e.printStackTrace(); // To change body of catch statement use File |
                             // Settings | File Templates.
    }

    // insert into Interesse (besteller_bestellerId, interesse, journal_id)
    // values (?, ?, ?)
    // insert into Nutzung (journal_id, nutzungsjahr, rechnungsbetrag,
    // zeitraum, zugriffe) values (?, ?, ?, ?, ?)
    // insert into Rechnung (betrag, bezugsform, bezugsjahr,
    // exemplar_exemplarId, sigel_sigelId) values (?, ?, ?, ?, ?)

}