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.NoteHelper.java

/**
 * Cette fonction permet de savoir si la Note d'un Concept existe ou non
 *
 * @param ds//from   w  w  w  .j  ava2  s .  co  m
 * @param idTerm
 * @param idThesaurus
 * @param idLang
 * @param noteTypeCode
 * @return boolean
 */
public boolean isNoteExistOfTerm(HikariDataSource ds, String idTerm, String idThesaurus, String idLang,
        String noteTypeCode) {

    Connection conn;
    Statement stmt;
    ResultSet resultSet;
    boolean existe = false;

    try {
        // Get connection from pool
        conn = ds.getConnection();
        try {
            stmt = conn.createStatement();
            try {
                String query = "select id from note" + " where id_term = '" + idTerm + "'"
                        + " and id_thesaurus = '" + idThesaurus + "'" + " and lang ='" + idLang + "'"
                        + " and noteTypeCode = '" + noteTypeCode + "'";
                stmt.executeQuery(query);
                resultSet = stmt.getResultSet();
                if (resultSet != null) {
                    resultSet.next();
                    existe = resultSet.getRow() != 0;
                }

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

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * Loads a bundle from the underlying system and optionally performs
 * a check on the bundle first.//w ww  .ja v  a 2s.  co m
 *
 * @param id the node id of the bundle
 * @param checkBeforeLoading check the bundle before loading it and log
 *                           detailed informations about it (slower)
 * @return the loaded bundle or <code>null</code> if the bundle does not
 *         exist.
 * @throws ItemStateException if an error while loading occurs.
 */
protected synchronized NodePropBundle loadBundle(NodeId id, boolean checkBeforeLoading)
        throws ItemStateException {
    ResultSet rs = null;
    InputStream in = null;
    byte[] bytes = null;
    try {
        Statement stmt = connectionManager.executeStmt(bundleSelectSQL, getKey(id.getUUID()));
        rs = stmt.getResultSet();
        if (!rs.next()) {
            return null;
        }
        Blob b = rs.getBlob(1);
        // JCR-1039: pre-fetch/buffer blob data
        long length = b.length();
        bytes = new byte[(int) length];
        in = b.getBinaryStream();
        int read, pos = 0;
        while ((read = in.read(bytes, pos, bytes.length - pos)) > 0) {
            pos += read;
        }
        DataInputStream din = new DataInputStream(new ByteArrayInputStream(bytes));

        if (checkBeforeLoading) {
            if (binding.checkBundle(din)) {
                // reset stream for readBundle()
                din = new DataInputStream(new ByteArrayInputStream(bytes));
            } else {
                // gets wrapped as proper ItemStateException below
                throw new Exception("invalid bundle, see previous BundleBinding error log entry");
            }
        }

        NodePropBundle bundle = binding.readBundle(din, id);
        bundle.setSize(length);
        return bundle;
    } catch (Exception e) {
        String msg = "failed to read bundle: " + id + ": " + e;
        log.error(msg);
        throw new ItemStateException(msg, e);
    } finally {
        IOUtils.closeQuietly(in);
        closeResultSet(rs);
    }
}

From source file:org.apache.gobblin.source.jdbc.JdbcExtractor.java

/**
 * Execute query using JDBC simple Statement Set fetch size
 *
 * @param cmds commands - query, fetch size
 * @return JDBC ResultSet/*from  www  .  j a v  a 2s.  c o m*/
 * @throws Exception
 */
private CommandOutput<?, ?> executeSql(List<Command> cmds) {
    String query = null;
    int fetchSize = 0;

    for (Command cmd : cmds) {
        if (cmd instanceof JdbcCommand) {
            JdbcCommandType type = (JdbcCommandType) cmd.getCommandType();
            switch (type) {
            case QUERY:
                query = cmd.getParams().get(0);
                break;
            case FETCHSIZE:
                fetchSize = Integer.parseInt(cmd.getParams().get(0));
                break;
            default:
                this.log.error("Command " + type.toString() + " not recognized");
                break;
            }
        }
    }

    this.log.info("Executing query:" + query);
    ResultSet resultSet = null;
    try {
        this.jdbcSource = createJdbcSource();
        if (this.dataConnection == null) {
            this.dataConnection = this.jdbcSource.getConnection();
        }
        Statement statement = this.dataConnection.createStatement();

        if (fetchSize != 0 && this.getExpectedRecordCount() > 2000) {
            statement.setFetchSize(fetchSize);
        }
        final boolean status = statement.execute(query);
        if (status == false) {
            this.log.error("Failed to execute sql:" + query);
        }
        resultSet = statement.getResultSet();
    } catch (Exception e) {
        this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e);
    }

    CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput();
    output.put((JdbcCommand) cmds.get(0), resultSet);
    return output;
}

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

/**
 * Cette fonction permet de savoir si la Note d'un Concept existe ou non
 *
 * @param ds//from w w w. j av a 2s.  com
 * @param idConcept
 * @param idThesaurus
 * @param idLang
 * @param noteTypeCode
 * @return boolean
 */
public boolean isNoteExistOfConcept(HikariDataSource ds, String idConcept, String idThesaurus, String idLang,
        String noteTypeCode) {

    Connection conn;
    Statement stmt;
    ResultSet resultSet;
    boolean existe = false;

    try {
        // Get connection from pool
        conn = ds.getConnection();
        try {
            stmt = conn.createStatement();
            try {
                String query = "select id from note" + " where id_concept = '" + idConcept + "'"
                        + " and id_thesaurus = '" + idThesaurus + "'" + " and lang ='" + idLang + "'"
                        + " and noteTypeCode = '" + noteTypeCode + "'";
                stmt.executeQuery(query);
                resultSet = stmt.getResultSet();
                if (resultSet != null) {
                    resultSet.next();
                    existe = resultSet.getRow() != 0;
                }

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

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

public Vector<DBRegisteredUsers> getRegisteredUsersEntries() {
    Vector<DBRegisteredUsers> retVect = new Vector<DBRegisteredUsers>();
    java.sql.Connection conn = null;
    try {//from  w  w w.j  a va2s.c o m
        Class.forName(jdbcdriverClassName).newInstance();
        conn = DriverManager.getConnection(connString, usrStr, pwdStr);
        String echomessage = "";
        if (!conn.isClosed()) {
            //echomessage =  "Successfully connected to "+ "MySQL server using TCP/IP...";
            Statement stmt = null;
            ResultSet rs = null;
            try {
                stmt = conn.createStatement();
                if (stmt.execute(
                        "SELECT idusers, passwd, login, email, idrole, role_name, lastadvtimestamp, disabled, FROM_UNIXTIME(lastadvtimestamp, \'%d/%m/%Y %H:%i:%s\') lastdate FROM vitrofrontenddb.roles AS r JOIN (vitrofrontenddb.userinrolesmr as ur JOIN vitrofrontenddb.users AS u ON u.idusers = ur.iduser) ON r.idroles=ur.idrole ")) {
                    rs = stmt.getResultSet();
                }
                if (rs != null) {
                    while (rs.next()) {
                        int userId = rs.getInt("idusers");
                        String passwd = rs.getString("passwd") == null ? "" : rs.getString("passwd"); // this is the one used in registration messages
                        String loginName = rs.getString("login") == null ? "" : rs.getString("login");
                        String emailAddress = rs.getString("email") == null ? "" : rs.getString("email");
                        String role_name = rs.getString("role_name") == null ? "" : rs.getString("role_name");
                        int role = rs.getInt("idrole");
                        int lastadvtimestampInt = rs.getInt("lastadvtimestamp");
                        String lastdate = rs.getString("lastdate") == null ? "N/A" : rs.getString("lastdate");
                        Boolean status = rs.getBoolean("disabled");
                        if (!loginName.isEmpty() && !loginName.equalsIgnoreCase("")) {
                            DBRegisteredUsers entryRegisterUsers = new DBRegisteredUsers(userId, loginName,
                                    passwd, emailAddress, role, role_name, lastadvtimestampInt, lastdate,
                                    status);
                            retVect.addElement(entryRegisterUsers);
                        }
                    }
                }
            } catch (SQLException ex) {
                // handle any errors
                System.out.println("SQLException: " + ex.getMessage());
                System.out.println("SQLState: " + ex.getSQLState());
                System.out.println("VendorError: " + 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) {
                        System.out.println("SQLException on rs close(): " + sqlEx.getMessage());
                    } // ignore
                    rs = null;
                }
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException sqlEx) {
                        System.out.println("SQLException on stmt close(): " + sqlEx.getMessage());
                    } // ignore
                    stmt = null;
                }
            }
        } else {
            echomessage = "Error accessing DB server...";
        }
        System.out.println(echomessage);
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
        }
    }
    return retVect;
}

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

synchronized public void updateStatusUser(String pUserRegisteredName) {
    java.sql.Connection conn = null;
    try {//from   w  w w.  j  a va 2s .com
        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 idusers, passwd, login, email, idrole, role_name, lastadvtimestamp, disabled, FROM_UNIXTIME(lastadvtimestamp, \'%d/%m/%Y %H:%i:%s\') lastdate FROM vitrofrontenddb.roles AS r JOIN (vitrofrontenddb.userinrolesmr as ur JOIN vitrofrontenddb.users AS u ON u.idusers = ur.iduser) ON r.idroles=ur.idrole ")) {
                    rs = stmt.getResultSet();
                }
                if (rs != null) {
                    while (rs.next()) {
                        int userId = rs.getInt("idusers");
                        String passwd = rs.getString("passwd") == null ? "" : rs.getString("passwd"); // this is the one used in registration messages
                        String loginName = rs.getString("login") == null ? "" : rs.getString("login");
                        String emailAddress = rs.getString("email") == null ? "" : rs.getString("email");
                        String role_name = rs.getString("role_name") == null ? "" : rs.getString("role_name");
                        int role = rs.getInt("idrole");
                        int lastadvtimestampInt = rs.getInt("lastadvtimestamp");
                        String lastdate = rs.getString("lastdate") == null ? "N/A" : rs.getString("lastdate");
                        Boolean status = rs.getBoolean("disabled");
                        if (loginName.equalsIgnoreCase(pUserRegisteredName)) {
                            if (status == false) {
                                if (stmt.execute(
                                        "UPDATE `" + dbSchemaStr + "`.`users` SET disabled = 1  WHERE login=\'"
                                                + pUserRegisteredName + "\'")) {
                                    rs = stmt.getResultSet(); // TODO: this is not needed here...
                                }
                            } else {
                                if (stmt.execute(
                                        "UPDATE `" + dbSchemaStr + "`.`users` SET disabled = 0  WHERE login=\'"
                                                + pUserRegisteredName + "\'")) {
                                    rs = stmt.getResultSet(); // TODO: this is not needed here...
                                }
                            }
                            break;
                        }
                    }
                }

            } 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:com.feedzai.commons.sql.abstraction.engine.impl.SqlServerEngine.java

protected void dropReferringFks(DbEntity entity) throws DatabaseEngineException {
    Statement s = null;
    ResultSet dependentTables = null;
    try {/*  w  w w. j  a v  a2  s.com*/
        /*
         * List of constraints that won't let the table be dropped.
         */
        s = conn.createStatement();
        final String sString = format(
                "SELECT T1.TABLE_NAME, CONSTRAINT_NAME "
                        + "FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE AS T1 "
                        + "JOIN SYS.FOREIGN_KEYS AS F " + "ON (F.parent_object_id = OBJECT_ID(N'%s') OR "
                        + "F.referenced_object_id = OBJECT_ID(N'%s')) AND "
                        + "T1.CONSTRAINT_NAME = OBJECT_NAME(F.object_id) AND " + "T1.TABLE_NAME NOT LIKE '%s'",
                entity.getName(), entity.getName(), entity.getName());

        logger.trace(sString);
        s.executeQuery(sString);

        dependentTables = s.getResultSet();

        while (dependentTables.next()) {

            Statement dropFk = null;
            try {
                dropFk = conn.createStatement();
                final String dropFkString = format("ALTER TABLE %s DROP CONSTRAINT %s",
                        quotize(dependentTables.getString(1)), quotize(dependentTables.getString(2)));
                logger.trace(dropFkString);
                dropFk.executeUpdate(dropFkString);

            } catch (SQLException ex) {
                logger.debug(format("Unable to drop constraint '%s' in table '%s'",
                        dependentTables.getString(2), dependentTables.getString(1)), ex);
            } finally {
                if (dropFk != null) {
                    try {
                        dropFk.close();
                    } catch (Exception e) {
                        logger.trace("Error closing statement.", e);
                    }
                }
            }
        }
    } catch (SQLException ex) {
        throw new DatabaseEngineException(
                format("Unable to drop foreign keys of the tables that depend on '%s'", entity.getName()), ex);
    } finally {
        if (dependentTables != null) {
            try {
                dependentTables.close();
            } catch (Exception e) {
                logger.trace("Error closing result set.", e);
            }
        }
        if (s != null) {
            try {
                s.close();
            } catch (Exception e) {
                logger.trace("Error closing statement.", e);
            }
        }
    }
}

From source file:org.apache.hive.jdbc.HiveConnection.java

private void executeInitSql() throws SQLException {
    if (initFile != null) {
        try {// www.  j  ava 2 s.com
            List<String> sqlList = parseInitFile(initFile);
            Statement st = createStatement();
            for (String sql : sqlList) {
                boolean hasResult = st.execute(sql);
                if (hasResult) {
                    ResultSet rs = st.getResultSet();
                    while (rs.next()) {
                        System.out.println(rs.getString(1));
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("Failed to execute initial SQL");
            throw new SQLException(e.getMessage());
        }
    }
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * {@inheritDoc}//from  w  ww.  j a  v  a 2 s.c  o  m
 */
public synchronized boolean exists(NodeReferencesId targetId) throws ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    ResultSet rs = null;
    try {
        Statement stmt = connectionManager.executeStmt(nodeReferenceSelectSQL,
                getKey(targetId.getTargetId().getUUID()));
        rs = stmt.getResultSet();

        // a reference exists if the result has at least one entry
        return rs.next();
    } catch (Exception e) {
        String msg = "failed to check existence of node references: " + targetId;
        log.error(msg, e);
        throw new ItemStateException(msg, e);
    } finally {
        closeResultSet(rs);
    }
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * {@inheritDoc}//ww w  .  ja  va  2 s  .  c o m
 */
public synchronized NodeReferences load(NodeReferencesId targetId)
        throws NoSuchItemStateException, ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    ResultSet rs = null;
    InputStream in = null;
    try {
        Statement stmt = connectionManager.executeStmt(nodeReferenceSelectSQL,
                getKey(targetId.getTargetId().getUUID()));
        rs = stmt.getResultSet();
        if (!rs.next()) {
            throw new NoSuchItemStateException(targetId.toString());
        }

        in = rs.getBinaryStream(1);
        NodeReferences refs = new NodeReferences(targetId);
        Serializer.deserialize(refs, in);

        return refs;
    } catch (Exception e) {
        if (e instanceof NoSuchItemStateException) {
            throw (NoSuchItemStateException) e;
        }
        String msg = "failed to read references: " + targetId;
        log.error(msg, e);
        throw new ItemStateException(msg, e);
    } finally {
        IOUtils.closeQuietly(in);
        closeResultSet(rs);
    }
}