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:net.refractions.udig.catalog.internal.postgis.ui.PostgisDatabaseConnectionRunnable.java

public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {

    try {//from  ww  w.j a  va2s . c  o  m

        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put(DBTYPE.key, (Serializable) new PostgisServiceDialect().dbType);
        params.put(HOST.key, host);
        params.put(PORT.key, port);
        params.put(USER.key, username);
        params.put(PASSWD.key, password);
        params.put(DATABASE.key, "template1");

        BasicDataSource source = PostgisServiceExtension2.getFactory().createDataSource(params);
        Connection connection = source.getConnection();
        try {

            Statement statement = connection.createStatement();
            if (statement.execute("SELECT datname FROM pg_database")) {
                ResultSet resultSet = statement.getResultSet();
                while (resultSet.next()) {
                    databaseNames.add(resultSet.getString("datname"));
                }
            }
            statement.close();
        } finally {
            if (connection != null) {
                connection.close();
            }
            if (source != null) {
                source.close();
            }
        }
    } catch (SQLException e) {
        checkSqlException(e);
    } catch (IOException e) {
        if (e.getCause() instanceof SQLException) {
            checkSqlException((SQLException) e.getCause());
        } else {
            PostgisPlugin.log("Error connecting to datasource", e);
            result = "Unrecognized connection failure.  Check parameters and database.";
        }
    }
    ran = true;
}

From source file:eu.udig.catalog.teradata.TeradataDatabaseConnectionRunnable.java

public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {

    try {//from w  w  w.j  a  v  a2 s .c  o m

        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put(DBTYPE.key, (Serializable) new TeradataDialect().dbType);
        params.put(HOST.key, host);
        params.put(PORT.key, port);
        params.put(USER.key, username);
        params.put(PASSWD.key, password);
        params.put(DATABASE.key, "dbc");

        BasicDataSource source = TeradataServiceExtension.getFactory().createDataSource(params);
        Connection connection = source.getConnection();
        try {

            Statement statement = connection.createStatement();
            if (statement.execute("SELECT F_TABLE_SCHEMA FROM SYSSPATIAL.GEOMETRY_COLUMNS")) {
                ResultSet resultSet = statement.getResultSet();
                while (resultSet.next()) {
                    databaseNames.add(resultSet.getString(1).trim());
                }
            }
            statement.close();
        } finally {
            if (connection != null) {
                connection.close();
            }
            if (source != null) {
                source.close();
            }
        }
    } catch (SQLException e) {
        checkSqlException(e);
    } catch (Exception e) {
        if (e.getCause() instanceof SQLException) {
            checkSqlException((SQLException) e.getCause());
        } else {
            Activator.log("Error connecting to datasource", e);
            result = "Unrecognized connection failure.  Check parameters and database.";
        }
    }
    ran = true;
}

From source file:com.splout.db.common.SQLiteJDBCManager.java

/**
 * The contract of this function is to return a JSON-ized ArrayList of JSON Objects which in Java are represented as
 * Map<String, Object>. So, for a query with no results, an empty ArrayList is returned.
 *///w  w  w. j  a  v  a 2s  .  co  m
public String query(String query, int maxResults) throws SQLException, JSONSerDeException {
    long start = System.currentTimeMillis();
    Connection connection = connectionPool.getConnection(); // fetch a connection
    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = connection.createStatement();
        String result = null;
        if (stmt.execute(query)) {
            rs = stmt.getResultSet();
            result = JSONSerDe.ser(convertResultSetToList(rs, maxResults));
        } else {
            result = JSONSerDe.ser(new ArrayList<HashMap<String, Object>>());
        }
        long end = System.currentTimeMillis();
        log.info(Thread.currentThread().getName() + ": Query [" + query + "] handled in [" + (end - start)
                + "] ms.");
        return result;
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        connection.close();
    }
}

From source file:com.linkedin.pinot.integration.tests.RealtimeClusterIntegrationTest.java

@BeforeClass
public void setUp() throws Exception {
    // Start ZK and Kafka
    startZk();//from www  .  j  ava  2 s.  c o  m
    kafkaStarters = KafkaStarterUtils.startServers(getKafkaBrokerCount(), KafkaStarterUtils.DEFAULT_KAFKA_PORT,
            KafkaStarterUtils.DEFAULT_ZK_STR, KafkaStarterUtils.getDefaultKafkaConfiguration());

    // Create Kafka topic
    createKafkaTopic(KAFKA_TOPIC, KafkaStarterUtils.DEFAULT_ZK_STR);

    // Start the Pinot cluster
    startController();
    startBroker();
    startServer();

    // Unpack data
    final List<File> avroFiles = unpackAvroData(_tmpDir, SEGMENT_COUNT);

    File schemaFile = getSchemaFile();

    // Load data into H2
    ExecutorService executor = Executors.newCachedThreadPool();
    setupH2AndInsertAvro(avroFiles, executor);

    // Initialize query generator
    setupQueryGenerator(avroFiles, executor);

    // Push data into the Kafka topic
    pushAvroIntoKafka(avroFiles, executor, KAFKA_TOPIC);

    // Wait for data push, query generator initialization and H2 load to complete
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.MINUTES);

    // Create Pinot table
    setUpTable("mytable", "DaysSinceEpoch", "daysSinceEpoch", KafkaStarterUtils.DEFAULT_ZK_STR, KAFKA_TOPIC,
            schemaFile, avroFiles.get(0));

    // Wait until the Pinot event count matches with the number of events in the Avro files
    long timeInFiveMinutes = System.currentTimeMillis() + 5 * 60 * 1000L;
    Statement statement = _connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    statement.execute("select count(*) from mytable");
    ResultSet rs = statement.getResultSet();
    rs.first();
    int h2RecordCount = rs.getInt(1);
    rs.close();

    waitForRecordCountToStabilizeToExpectedCount(h2RecordCount, timeInFiveMinutes);
}

From source file:gsn.vsensor.TestStreamExporterVirtualSensor.java

public void testLogStatementIntoMySQLDB() {
    StreamExporterVirtualSensor vs = new StreamExporterVirtualSensor();
    // configure parameters
    ArrayList<KeyValue> params = new ArrayList<KeyValue>();
    params.add(new KeyValueImp(StreamExporterVirtualSensor.PARAM_URL, url));
    params.add(new KeyValueImp(StreamExporterVirtualSensor.PARAM_USER, user));
    params.add(new KeyValueImp(StreamExporterVirtualSensor.PARAM_PASSWD, passwd));
    config.setMainClassInitialParams(params);
    vs.setVirtualSensorConfiguration(config);
    vs.initialize();//from w  w  w  . j a v a 2  s .c  om

    // configure datastream
    Vector<DataField> fieldTypes = new Vector<DataField>();
    Object[] data = null;

    for (String type : DataTypes.TYPE_NAMES)
        fieldTypes.add(new DataField(type, type, type));
    int i = 0;
    for (Object value : DataTypes.TYPE_SAMPLE_VALUES)
        data[i++] = value;

    long timeStamp = new Date().getTime();
    StreamElement streamElement = new StreamElement(fieldTypes.toArray(new DataField[] {}),
            (Serializable[]) data, timeStamp);

    // give datastream to vs
    vs.dataAvailable(streamName, streamElement);

    // clean up and control
    boolean result = true;
    try {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        Connection connection = DriverManager.getConnection(url, user, passwd);
        Statement statement = connection.createStatement();
        statement.execute("SELECT * FROM " + streamName);
        System.out.println("result" + result);
        result = statement.getResultSet().last();
        System.out.println("result" + result);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        result = false;
    }
    assertTrue(result);
}

From source file:com.sangupta.fileanalysis.db.DBResultViewer.java

/**
 * View results of a {@link Statement}./*ww  w .j  a v a  2 s.c om*/
 * 
 * @param statement
 * @throws SQLException
 */
public void viewResult(Statement statement) throws SQLException {
    if (statement == null) {
        // nothing to do
        return;
    }

    if (statement.getResultSet() != null) {
        // results were obtained
        viewResult(statement.getResultSet());
        return;
    }

    // we do not have any result set
    // may be an update count etc?
    System.out.println("Records updated: " + statement.getUpdateCount());
}

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

static private void appendPossibleEntityTableDetails(SqlDalDatabase sqldb, String sql, StringBuilder sb)
        throws DalDbException {

    Connection conn = null;//from ww  w.ja  v a  2  s  .c o  m
    Statement stmt = null;
    ResultSet rs = null;
    try {

        conn = sqldb.getConnection(false);

        stmt = conn.createStatement();

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

        boolean hasResultSet = stmt.execute(sql);

        if (hasResultSet) {
            rs = stmt.getResultSet();
            DalServerUtil.appendResultSetRowsAsTable("No entity table", rs, sb);
        } else {
            int n = stmt.getUpdateCount();
            sb.append("Update count=").append(n);
        }
    } catch (SQLException e) {
        throw new DalDbException(e);
    } finally {
        SqlUtil.closeSandRS(stmt, rs);
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
        }
    }

}

From source file:com.splout.db.engine.JDBCManager.java

public QueryResult query(String query, int maxResults) throws EngineException {
    long start = System.currentTimeMillis();
    Connection connection = null;
    ResultSet rs = null;/*  w w  w  .  j  a  v  a 2s .c  o  m*/
    Statement stmt = null;
    try {
        connection = connectionPool.getConnection(); // fetch a connection
        stmt = connection.createStatement();
        QueryResult result = null;
        if (stmt.execute(query)) {
            rs = stmt.getResultSet();
            result = convertResultSetToQueryResult(rs, maxResults);
        } else {
            result = QueryResult.emptyQueryResult();
        }
        long end = System.currentTimeMillis();
        log.info(Thread.currentThread().getName() + ": Query [" + query + "] handled in [" + (end - start)
                + "] ms.");
        return result;
    } catch (SQLException e) {
        throw convertException(e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            connection.close();
        } catch (SQLException e) {
            throw convertException(e);
        }
    }
}

From source file:org.apache.kylin.jdbc.ITJDBCDriverTest.java

@Test
public void testResultSet() 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.execute(sql);/*w w  w  .j  ava 2  s  .c o m*/

    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 > 0);
    statement.close();
    rs.close();
    conn.close();

}

From source file:org.apache.kylin.jdbc.ITJDBCDriverTest.java

@Test
public void testSimpleStatement() throws Exception {
    Connection conn = getConnection();
    Statement statement = conn.createStatement();

    statement.execute("select count(*) from test_kylin_fact");

    ResultSet rs = statement.getResultSet();

    Assert.assertTrue(rs.next());//from w ww .  j ava 2 s .co  m
    int result = rs.getInt(1);

    Assert.assertTrue(result > 0);

    rs.close();
    statement.close();
    conn.close();

}