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.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java

/**
 * {@inheritDoc}//from  www .j  a  v  a2s  .  c  om
 */
public NodeReferences loadReferencesTo(NodeId targetId) throws NoSuchItemStateException, ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    synchronized (nodeReferenceSelectSQL) {
        ResultSet rs = null;
        InputStream in = null;
        try {
            Statement stmt = executeStmt(nodeReferenceSelectSQL, new Object[] { targetId.toString() });
            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 node references: " + targetId;
            log.error(msg, e);
            throw new ItemStateException(msg, e);
        } finally {
            IOUtils.closeQuietly(in);
            closeResultSet(rs);
        }
    }
}

From source file:org.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java

/**
 * {@inheritDoc}//from   www. j a va 2 s  .  c o m
 */
public PropertyState load(PropertyId id) throws NoSuchItemStateException, ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    synchronized (propertyStateSelectSQL) {
        ResultSet rs = null;
        InputStream in = null;
        try {
            Statement stmt = executeStmt(propertyStateSelectSQL, new Object[] { id.toString() });
            rs = stmt.getResultSet();
            if (!rs.next()) {
                throw new NoSuchItemStateException(id.toString());
            }

            in = rs.getBinaryStream(1);

            if (!externalBLOBs) {
                // JCR-1532: pre-fetch/buffer stream data
                ByteArrayInputStream bain = new ByteArrayInputStream(IOUtils.toByteArray(in));
                IOUtils.closeQuietly(in);
                in = bain;
            }

            PropertyState state = createNew(id);
            Serializer.deserialize(state, in, blobStore);

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

From source file:com.feedzai.commons.sql.abstraction.engine.impl.MySqlEngine.java

protected void dropReferringFks(DbEntity entity) throws DatabaseEngineException {
    Statement s = null;
    ResultSet dependentTables = null;
    try {//from   ww w .j  a v  a2 s. c  o m
        /*
         * List of constraints that won't let the table be dropped.
         */
        s = conn.createStatement();
        final String sString = format("SELECT TABLE_NAME, CONSTRAINT_NAME "
                + "FROM information_schema.KEY_COLUMN_USAGE " + "WHERE REFERENCED_TABLE_NAME = '%s'",
                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 FOREIGN KEY %s",
                        quotize(dependentTables.getString(1), escapeCharacter()),
                        quotize(dependentTables.getString(2), escapeCharacter()));
                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 (Throwable e) {
            }
        }
        if (s != null) {
            try {
                s.close();
            } catch (Throwable e) {
            }
        }
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorIT.java

public void testLoadTable1() throws Exception {
    IPentahoSession session = new StandaloneSession("test");
    KettleSystemListener.environmentInit(session);
    ModelInfo info = createModel();//w  w  w.  j  ava  2  s .  co m
    CsvTransformGenerator gen = new CsvTransformGenerator(info, getDatabaseMeta());

    // create the model
    String tableName = info.getStageTableName();
    try {
        gen.execSqlStatement(getDropTableStatement(tableName), getDatabaseMeta(), null);
    } catch (CsvTransformGeneratorException e) {
        // table might not be there yet, it is OK
    }

    // generate the database table
    gen.createOrModifyTable(session);

    // load the table
    loadTable(gen, info, true, session);

    // check the results
    long rowCount = this.getRowCount(tableName);
    assertEquals((long) 235, rowCount);
    DatabaseMeta databaseMeta = getDatabaseMeta();
    assertNotNull(databaseMeta);
    Database database = new Database(databaseMeta);
    assertNotNull(database);
    database.connect();

    Connection connection = null;
    Statement stmt = null;
    ResultSet sqlResult = null;

    try {
        connection = database.getConnection();
        assertNotNull(connection);
        stmt = database.getConnection().createStatement();

        // check the first row
        Date testDate = new Date();
        testDate.setDate(1);
        testDate.setHours(0);
        testDate.setMinutes(0);
        testDate.setMonth(0);
        testDate.setSeconds(0);
        testDate.setYear(110);
        boolean ok = stmt.execute("select * from " + tableName);
        assertTrue(ok);
        sqlResult = stmt.getResultSet();
        assertNotNull(sqlResult);
        ok = sqlResult.next();
        assertTrue(ok);

        // test the values
        assertEquals((long) 3, sqlResult.getLong(1));
        assertEquals(25677.96525, sqlResult.getDouble(2));
        assertEquals((long) 1231, sqlResult.getLong(3));
        assertEquals(testDate.getYear(), sqlResult.getDate(4).getYear());
        assertEquals(testDate.getMonth(), sqlResult.getDate(4).getMonth());
        assertEquals(testDate.getDate(), sqlResult.getDate(4).getDate());
        assertEquals(testDate.getHours(), sqlResult.getTime(4).getHours());
        //    assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing?
        assertEquals(testDate.getSeconds(), sqlResult.getTime(4).getSeconds());

        //    assertEquals( testDate, cells[3] );
        assertEquals("Afghanistan", sqlResult.getString(5));
        assertEquals((long) 11, sqlResult.getLong(6));
        assertEquals(111.9090909, sqlResult.getDouble(7));
        assertEquals(false, sqlResult.getBoolean(8));
    } finally {
        sqlResult.close();
        stmt.close();
        connection.close();
    }

}

From source file:capture.MySQLDatabase.java

public boolean resumeLastOperation() {
    Connection con = this.getConnection();
    Statement stmt;
    ResultSet rs;//from   w ww.  ja va  2s. c o  m
    String operationid = null;
    String serverip = ConfigManager.getInstance().getConfigOption("server-listen-address");
    boolean result = false;
    long count = 0;
    try {
        Element e;
        stmt = con.createStatement();

        //find the last operation which still has unvisited urls.
        stmt.executeQuery("SELECT DISTINCT a.operation_id from url_operation a, operation b, honeypot c "
                + "WHERE a.operation_id=b.operation_id AND b.honeypot_id=c.honeypot_id AND a.status_id IS NULL "
                + " AND c.ipaddress=\'" + serverip + "\' order by operation_id DESC");
        rs = stmt.getResultSet();
        if (rs.next()) {

            operationid = rs.getString(1);
            System.out.println("System is going to inspect urls in the operation: " + operationid);
            Database.getInstance().setCurrentOperation(operationid);
            setSystemStatus(true);

            //update visit start time for operation if it hasn't set yet
            SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.S");
            String date = sf.format(new Date());
            stmt.executeUpdate("UPDATE operation SET visitstarttime=\'" + date + "\' " + "WHERE operation_id="
                    + operationid + " AND visitstarttime IS NULL");

            //get all urls which haven't been visited yet
            stmt.executeQuery("SELECT url.url_id, url.url FROM url, url_operation "
                    + "WHERE url_operation.url_id=url.url_id AND (url_operation.status_id IS NULL) AND url_operation.operation_id="
                    + operationid);
            rs = stmt.getResultSet();
            while (rs.next()) {
                e = new Element();
                e.name = "url";
                e.attributes.put("add", "");
                e.attributes.put("id", rs.getString(1));
                e.attributes.put("url", rs.getString(2));
                EventsController.getInstance().notifyEventObservers(e);
                count++;
            }
        }
        stmt.close();
        con.close();
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("******** RESUME: " + count + " URLs have been loaded! ********");
    return result;
}

From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java

public void testShowGrant() throws SQLException {
    Statement stmt = con.createStatement();
    stmt.execute("grant select on table " + dataTypeTableName + " to user hive_test_user");
    stmt.execute("show grant user hive_test_user on table " + dataTypeTableName);

    ResultSet res = stmt.getResultSet();
    assertTrue(res.next());/*from   w ww  . ja  v  a  2s  . c om*/
    assertEquals("default", res.getString(1));
    assertEquals(dataTypeTableName, res.getString(2));
    assertEquals("", res.getString(3)); // partition
    assertEquals("", res.getString(4)); // column
    assertEquals("hive_test_user", res.getString(5));
    assertEquals("USER", res.getString(6));
    assertEquals("Select", res.getString(7));
    assertEquals(false, res.getBoolean(8)); // grant option
    assertEquals(-1, res.getLong(9));
    assertNotNull(res.getString(10)); // grantor
    assertFalse(res.next());
    res.close();
}

From source file:com.cloud.utils.db.TransactionLegacy.java

protected void removeUpTo(String type, Object ref) {
    boolean rollback = false;
    Iterator<StackElement> it = _stack.iterator();
    while (it.hasNext()) {
        StackElement item = it.next();//w ww . j a  v  a2 s .  c o  m

        it.remove();

        try {
            if ((type == null || type.equals(item.type)) && (ref == null || ref.equals(item.ref))) {
                break;
            }

            if (item.type == CURRENT_TXN) {
                if (s_logger.isTraceEnabled()) {
                    s_logger.trace("Releasing the current txn: " + (item.ref != null ? item.ref : ""));
                }
            } else if (item.type == CREATE_CONN) {
                closeConnection();
            } else if (item.type == START_TXN) {
                if (item.ref == null) {
                    rollback = true;
                } else {
                    try {
                        _conn.rollback((Savepoint) ref);
                        rollback = false;
                    } catch (final SQLException e) {
                        s_logger.warn("Unable to rollback Txn.", e);
                    }
                }
            } else if (item.type == STATEMENT) {
                try {
                    if (s_stmtLogger.isTraceEnabled()) {
                        s_stmtLogger.trace("Closing: " + ref.toString());
                    }
                    Statement stmt = (Statement) ref;
                    try {
                        ResultSet rs = stmt.getResultSet();
                        if (rs != null) {
                            rs.close();
                        }
                    } catch (SQLException e) {
                        s_stmtLogger.trace("Unable to close resultset");
                    }
                    stmt.close();
                } catch (final SQLException e) {
                    s_stmtLogger.trace("Unable to close statement: " + item);
                }
            } else if (item.type == ATTACHMENT) {
                TransactionAttachment att = (TransactionAttachment) item.ref;
                if (s_logger.isTraceEnabled()) {
                    s_logger.trace("Cleaning up " + att.getName());
                }
                att.cleanup();
            }
        } catch (Exception e) {
            s_logger.error("Unable to clean up " + item, e);
        }
    }

    if (rollback) {
        rollback();
    }
}

From source file:org.alinous.plugin.mysql.MySQLDataSource.java

@Override
public DataTable[] getDataTableList(Object connectionHandle) throws DataSourceException {
    ArrayList<DataTable> list = new ArrayList<DataTable>();
    ArrayList<String> tables = new ArrayList<String>();

    // enum tables
    String sql = "SELECT TABLENAME as tblname FROM PG_TABLES WHERE TABLENAME NOT LIKE'pg%' AND TABLENAME NOT LIKE'sql_%' ORDER BY TABLENAME";

    PostgreSqlConnection con = (PostgreSqlConnection) connectionHandle;
    Statement stmt = null;

    try {/*from   www .  java 2s. c  o  m*/
        stmt = con.createStatement();

        stmt.execute(sql);

        ResultSet rs = stmt.getResultSet();
        while (rs.next()) {
            String tableName = rs.getString(1); // metaData.getColumnName(1);

            tables.add(tableName);
        }

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

    Iterator<String> it = tables.iterator();
    while (it.hasNext()) {
        String key = it.next();
        DataTable dataTable = getDataTable(connectionHandle, key);

        if (dataTable != null) {
            list.add(dataTable);
        }
    }

    return list.toArray(new DataTable[list.size()]);
}

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

public Vector<String> getRegisteredUserRegNames() {
    Vector<String> retVect = new Vector<String>();
    java.sql.Connection conn = null;
    try {/*w w w .java  2  s  .  c om*/
        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 login FROM `" + dbSchemaStr + "`.`users` ")) {
                    rs = stmt.getResultSet();
                }
                if (rs != null) {
                    while (rs.next()) {
                        String registeredLogin = rs.getString("login") == null ? "" : rs.getString("login");
                        if (!registeredLogin.isEmpty() && !registeredLogin.equalsIgnoreCase("")) {
                            retVect.add(registeredLogin);
                        }
                    }
                }
            } catch (SQLException ex) {
                // handle any errors
                System.err.println("SQLException2: " + ex.getMessage());
                System.err.println("SQLState2: " + ex.getSQLState());
                System.err.println("VendorError2: " + 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...";
        }
        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

public Vector<String> getRegisteredGatewayRegNames() {
    Vector<String> retVect = new Vector<String>();
    java.sql.Connection conn = null;
    try {//  w w w .j  ava  2  s  .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 registeredName FROM `" + dbSchemaStr + "`.`registeredgateway` ")) {
                    rs = stmt.getResultSet();
                }
                if (rs != null) {
                    while (rs.next()) {
                        String registeredName = rs.getString("registeredName") == null ? ""
                                : rs.getString("registeredName");
                        if (!registeredName.isEmpty() && !registeredName.equalsIgnoreCase("")) {
                            retVect.add(registeredName);
                        }
                    }
                }
            } catch (SQLException ex) {
                // handle any errors
                System.err.println("SQLException2: " + ex.getMessage());
                System.err.println("SQLState2: " + ex.getSQLState());
                System.err.println("VendorError2: " + 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...";
        }
        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;
}