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.kylin.jdbc.ITJDBCDriverTest.java

@Test
public void testResultSetWithMaxRows() throws Exception {
    String sql = "select LSTG_FORMAT_NAME, sum(price) as GMV, count(1) as TRANS_CNT from test_kylin_fact \n"
            + " group by LSTG_FORMAT_NAME ";

    Connection conn = getConnection();
    Statement statement = conn.createStatement();
    statement.setMaxRows(2);/*from   w  w  w  . j a  v a2  s.c  o  m*/

    statement.execute(sql);

    ResultSet rs = statement.getResultSet();

    int count = 0;
    while (rs.next()) {
        count++;
        String lstg = rs.getString(1);
        double gmv = rs.getDouble(2);
        int trans_count = rs.getInt(3);

        System.out.println(
                "Get a line: LSTG_FORMAT_NAME=" + lstg + ", GMV=" + gmv + ", TRANS_CNT=" + trans_count);
    }

    Assert.assertTrue(count == 2);
    statement.close();
    rs.close();
    conn.close();

}

From source file:org.hyperic.hq.plugin.postgresql.ServerMeasurement.java

private void findPid(Metric metric) throws PluginException {
    Properties props = metric.getProperties();
    String user = props.getProperty(PostgreSQL.PROP_USER);
    String pass = props.getProperty(PostgreSQL.PROP_PASS);
    String url = PostgreSQL.prepareUrl(props, null);

    String newConfig = url + "-" + user + "-" + pass;
    boolean isNewConfig = !newConfig.equalsIgnoreCase(actualConfig);
    if (isNewConfig) {
        log.debug("[findPid] new config detected");
        actualConfig = newConfig;//from   ww w  . j  av a2  s  . com
    }

    // look for the PID 
    // IF config have changed (to test is the new config is valid)
    // OR no PID
    // OR always for Availability
    if (isNewConfig || (pid == -1) || (metric.isAvail())) {

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            conn = DriverManager.getConnection(url, user, pass);
            stmt = conn.createStatement();
            stmt.execute("select pg_backend_pid()");

            rs = stmt.getResultSet();
            if (rs.next()) {
                int conectionPid = rs.getInt(1);
                pid = new Sigar().getProcState(conectionPid).getPpid();
                log.debug("[findPid] conection PID:" + conectionPid + " ==> main Process PID:" + pid);
            }
        } catch (SQLException ex) {
            pid = -1;
            throw new PluginException(ex.getMessage(), ex);
        } catch (SigarException ex) {
            pid = -1;
            throw new PluginException(ex.getMessage(), ex);
        } finally {
            DBUtil.closeJDBCObjects(getLog(), conn, stmt, rs);
        }
    }
}

From source file:org.jiemamy.utils.sql.SqlExecutor.java

void executeSingleSql(String sql, SqlExecutorHandler handler) throws SQLException {
    logger.info(LogMarker.DETAIL, sql);/*from  w ww.j  a  va2 s . c o m*/

    boolean isAutoCommit = connection.getAutoCommit();
    connection.setAutoCommit(false);

    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = connection.createStatement();

        if (stmt.execute(sql)) {
            if (handler != null) {
                rs = stmt.getResultSet();
                handler.handleResultSet(sql, rs);
            }
        } else {
            if (handler != null) {
                int count = stmt.getUpdateCount();
                if (count >= 0) {
                    handler.handleUpdateCount(sql, count);
                }
            }
        }

        connection.commit();
    } catch (SQLException e) {
        logger.warn(sql, e);
        connection.rollback();
        throw e;
    } finally {
        connection.setAutoCommit(isAutoCommit);
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
    }
}

From source file:com.ianzepp.logging.jms.service.BasicDaoTest.java

/**
 * TODO Method description for <code>testSaveEvent()</code>
 * //from ww w .j ava2s  . c o  m
 * @throws Exception
 */
@Test
public final void testSaveEvent() throws Exception {
    // Save the id first
    HashMap<String, Object> paramMap = newInitializedEventMap(UUID.randomUUID());

    // Run the save
    assertTrue(newInitializedInstance().executeQuery("InsertEvent", paramMap) > 0);

    // Test the result
    String statementSql = "SELECT * FROM \"Event\" WHERE \"Id\" = '" + paramMap.get("Id") + "'";
    Statement statement = getConnection().createStatement();

    // Check the query
    assertTrue(statement.execute(statementSql));

    // Check the result set
    ResultSet resultSet = statement.getResultSet();

    assertTrue("No result set data was returned.", resultSet.first());

    for (String columnName : paramMap.keySet()) {
        assertEquals(paramMap.get(columnName), resultSet.getString(columnName));
    }

    assertFalse("Too many results were returned", resultSet.next());
}

From source file:org.dbinterrogator.mssql.MSSQLInstance.java

/**
 * List Databases// w  w w. j av  a  2  s .  c o  m
 *
 * @return List of databases
 */
public ArrayList<String> listDatabases() {
    ArrayList<String> databases = new ArrayList();
    try {
        Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        s.executeQuery("SELECT name FROM sys.databases");
        ResultSet rs = s.getResultSet();
        while (rs.next()) {
            databases.add(rs.getString(1));
        }
    } catch (SQLException e) {
        System.err.println(e.getMessage());
    }
    if (verbose) {
        System.out.println(databases);
    }
    return databases;
}

From source file:org.dbinterrogator.mssql.MSSQLInstance.java

/**
 * List Views//  www. j  av  a2  s  .co m
 *
 * @param  db  Database Name
 * @return List of tables for selected database
 */
public ArrayList<String> listViews(String db) {
    ArrayList<String> views = new ArrayList();
    try {
        Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        s.executeQuery("SELECT name FROM [" + db + "].sys.views");
        ResultSet rs = s.getResultSet();
        while (rs.next()) {
            views.add(rs.getString(1));
        }
    } catch (SQLException e) {
        System.err.println(e.getMessage());
    }
    if (verbose) {
        System.out.println(views);
    }
    return views;
}

From source file:org.dbinterrogator.mssql.MSSQLInstance.java

/**
 * List Tables/*from   w ww.  j a  v a 2 s .c  o m*/
 *
 * @param  db  Database Name
 * @return List of tables for selected database
 */
public ArrayList<String> listTables(String db) {
    ArrayList<String> tables = new ArrayList();
    try {
        Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        s.executeQuery("SELECT name FROM [" + db + "].sys.tables");
        ResultSet rs = s.getResultSet();
        while (rs.next()) {
            tables.add(rs.getString(1));
        }
    } catch (SQLException e) {
        System.err.println(e.getMessage());
    }
    if (verbose) {
        System.out.println(tables);
    }
    return tables;
}

From source file:wikipedia.sql.Links.java

/** Selects one pl_title from pagelinks by pl_from. It is needed for 
 * redirect pages, which links only to one page. 
 * @return null, if (1) it is absent (e.g. it's redirect to category) or 
 *                  (2) title should be skipped
 */// w ww.ja  v a  2 s.c o m
public static String getTitleToOneByIDFrom(SessionHolder session, int pl_from) {
    if (0 == pl_from)
        return null;

    // special treatment of id of redirect page
    if (pl_from < 0)
        pl_from = -pl_from;

    Statement s = null;
    ResultSet rs = null;
    String title = null;

    sb.setLength(0);
    sb.append("SELECT pl_title FROM pagelinks WHERE pl_from=");
    sb.append(pl_from);
    sb.append(" LIMIT 1");

    try {
        s = session.connect.conn.createStatement();
        //str_sql = SELECT pl_title FROM pagelinks WHERE pl_from=52141 LIMIT 1;

        s.executeQuery(sb.toString());
        rs = s.getResultSet();

        if (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)) {
                title = utf8_str;
            }
        }
    } catch (SQLException ex) {
        System.err.println("SQLException (Links.java getTitleToOneByIDFrom): 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 title;
}

From source file:com.dattack.dbtools.drules.engine.SourceExecutor.java

private ResultSet executeStatement(final Statement statement, final String sql) throws SQLException {

    LOGGER.info("Executing SQL sentence [{}@{}]: {}", Thread.currentThread().getName(), sourceBean.getId(),
            sql);/*from  w  w w . ja  v  a 2 s.co  m*/

    final boolean isResultSet = statement.execute(sql);

    if (isResultSet) {
        return statement.getResultSet();
    }

    return null;
}

From source file:org.apache.cayenne.migration.Migrator.java

Integer executeSqlReturnInt(String sql) throws SQLException {
    Statement st = null;
    JdbcEventLogger logger = node.getJdbcEventLogger();
    try {//from   ww w  .j a v a2  s.c o m
        logger.log(sql);
        st = getConnection().createStatement();
        try {
            st.execute(sql);
            ResultSet rs = st.getResultSet();
            if (rs != null && rs.next()) {
                return rs.getInt(1);
            } else {
                return null;
            }
        } catch (SQLException e) {
            getConnection().rollback();
            throw new RuntimeException("SQL statement failed \"" + sql + "\": " + e.getMessage(), e);
        }
    } finally {
        closeStatement(st);
    }
}