Example usage for java.sql ResultSet close

List of usage examples for java.sql ResultSet close

Introduction

In this page you can find the example usage for java.sql ResultSet close.

Prototype

void close() throws SQLException;

Source Link

Document

Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

Usage

From source file:net.hydromatic.foodbench.Main.java

/** Does the work. */
private void run(String jdbcUrl, String catalog, String driverClassName)
        throws IOException, SQLException, ClassNotFoundException {
    URL url = FoodMartQuery.class.getResource("/queries.json");
    InputStream inputStream = url.openStream();
    ObjectMapper mapper = new ObjectMapper();
    Map values = mapper.readValue(inputStream, Map.class);
    //noinspection unchecked
    List<Map<String, Object>> tests = (List) values.get("queries");
    if (driverClassName != null) {
        Class.forName(driverClassName);
    }/*from   w  w  w .  j  a v a  2 s.  co m*/
    Connection connection = DriverManager.getConnection(jdbcUrl);
    if (catalog != null) {
        connection.setCatalog(catalog);
    }
    Statement statement = connection.createStatement();
    for (Map<String, Object> test : tests) {
        int id = (Integer) test.get("id");
        if (!idSet.contains(id)) {
            continue;
        }
        String sql = (String) test.get("sql");
        if (jdbcUrl.startsWith("jdbc:mysql:")) {
            sql = sql.replace("\"", "`");
            sql = sql.replace(" NULLS FIRST", "");
            sql = sql.replace(" NULLS LAST", "");
            if (sql.contains("VALUES ")) {
                System.out.println("query id: " + id + " sql: " + sql + " skipped");
                continue;
            }
        }
        if (jdbcUrl.startsWith("jdbc:optiq:")) {
            sql = sql.replace("RTRIM(", "TRIM(TRAILING ' ' FROM ");
        }
        final AtomicLong tPrepare = new AtomicLong(0);
        Hook.Closeable hook = Hook.JAVA_PLAN.add(new Function1<Object, Object>() {
            public Object apply(Object a0) {
                tPrepare.set(System.nanoTime());
                return null;
            }
        });
        try {
            final long t0 = System.nanoTime();
            ResultSet resultSet = statement.executeQuery(sql);
            int n = 0;
            while (resultSet.next()) {
                ++n;
            }
            resultSet.close();
            final long tEnd = System.nanoTime();
            final long nanos = tEnd - t0;
            final long prepare = tPrepare.longValue() - t0;
            final long execute = tEnd - tPrepare.longValue();
            System.out.println("query id: " + id + " rows: " + n + " nanos: " + NF.format(nanos) + " prepare: "
                    + NF.format(prepare) + " execute: " + NF.format(execute) + " prepare%: "
                    + ((float) prepare / (float) nanos * 100f));
        } catch (SQLException e) {
            System.out.println("query id: " + id + " sql: " + sql + " error: " + e.getMessage());
            if (verbose) {
                e.printStackTrace();
            }
        } finally {
            hook.close();
        }
    }
    statement.close();
    connection.close();
}

From source file:com.foundationdb.server.service.security.SecurityServiceIT.java

@Test
public void postgresAuthenticated() throws Exception {
    Connection conn = openPostgresConnection("user1", "password");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT id FROM utable");
    assertTrue(rs.next());/*from   w  ww  .j a  va2 s. co  m*/
    assertEquals(1, rs.getInt(1));
    rs.close();
    stmt.execute("DROP TABLE utable");
    stmt.close();
    conn.close();
}

From source file:org.openmrs.module.xreports.api.db.hibernate.HibernateXReportsDAO.java

/**
 * @see org.openmrs.module.xreports.api.db.XReportsDAO#getSqlIntValue(java.lang.String)
 *//*w w w .  j a va2  s  .com*/
@Override
public Integer getSqlIntValue(String sql) throws Exception {
    Integer value = null;
    Statement statement = sessionFactory.getCurrentSession().connection().createStatement();
    ResultSet res = statement.executeQuery(sql);
    if (res.next()) {
        value = res.getInt(1);
        if (res.wasNull()) {
            value = null;
        }
    }
    res.close();
    statement.close();
    return value;
}

From source file:de.ingrid.importer.udk.strategy.v1.IDCStrategy1_0_6_fixSysListInspire.java

private int readCatalogLanguageKey() throws Exception {
    int langKey = -1;
    String sql = "SELECT language_key FROM t03_catalogue";
    try {/*  w w  w.  ja  v  a 2  s. co m*/
        Statement st = jdbc.createStatement();
        ResultSet rs = jdbc.executeQuery(sql, st);
        // has to be there !!!
        rs.next();

        langKey = rs.getInt(1);

        rs.close();
        st.close();

    } catch (SQLException e) {
        log.error("Error executing SQL: " + sql, e);
        throw e;
    }

    return langKey;
}

From source file:at.ac.tuwien.dsg.dataassetloader.store.DataAssetFunctionStore.java

public int getNoOfPartitions(String dataAssetID) {

    int noOfPartition = 0;

    String sql = "select * from DataAssetFunction WHERE dataAssetID='" + dataAssetID + "'";
    ResultSet rs = connectionManager.ExecuteQuery(sql);

    try {// w w w  . j  av a  2 s .c  om
        while (rs.next()) {
            noOfPartition = rs.getInt("noOfPartition");
        }

        rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataAssetFunctionStore.class.getName()).log(Level.SEVERE, null, ex);
    }

    return noOfPartition;
}

From source file:com.nabla.dc.server.handler.fixed_asset.UpdateAssetDisposalHandler.java

private Date getAssetAcqisitionDate(final Connection conn, int assetId) throws SQLException, ActionException {
    final PreparedStatement stmt = StatementFormat.prepare(conn,
            "SELECT acquisition_date FROM fa_asset WHERE id=?;", assetId);
    try {/*from w ww  . jav  a 2 s .  c o m*/
        final ResultSet rs = stmt.executeQuery();
        try {
            if (!rs.next())
                throw new ActionException(CommonServerErrors.RECORD_HAS_BEEN_REMOVED);
            return rs.getDate(1);
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }
}

From source file:id.go.kemenkeu.djpk.usermanagement.service.impl.PemdaServiceTest.java

@Test
public void testInsertBanyak() throws Exception {
    Tprov prov = new Tprov();
    prov.setId(99);//ww  w. jav a2 s .c om

    //Simpan banyak
    List<Object> daftarPemda = new ArrayList<Object>();
    Pemda p = new Pemda();
    p.setKode("P-001");
    p.setKodeSatuanKerja("ABC0");
    p.setUraian("Pemda Tester");
    p.setUraianSingkat("Tester");
    p.setProvinsi(prov);
    daftarPemda.add(p);

    Pemda p1 = new Pemda();
    p1.setKode("P-002");
    p1.setKodeSatuanKerja("ABC1");
    p1.setUraian("Pemda Tester");
    p1.setUraianSingkat("Tester");
    p1.setProvinsi(prov);
    daftarPemda.add(p1);

    Pemda p2 = new Pemda();
    p2.setKode("P-003");
    p2.setKodeSatuanKerja("ABC2");
    p2.setUraian("Pemda Tester");
    p2.setUraianSingkat("Tester");
    p2.setProvinsi(prov);
    daftarPemda.add(p2);

    ums.simpanBanyak(daftarPemda);

    String sqlCek = "select count(*) from tpemda";
    Connection conn = dataSource.getConnection();

    ResultSet rs = conn.createStatement().executeQuery(sqlCek);
    Assert.assertTrue(rs.next());

    Long count = rs.getLong(1);
    Assert.assertEquals(new Long(4), count);

    rs.close();
    conn.close();
}

From source file:com.predic8.membrane.examples.tests.LoggingJDBCTest.java

private void assertLogToDerbySucceeded(File baseDir)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
    String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    Class.forName(driver).newInstance();

    File db = new File(baseDir, "derbyDB");
    Connection conn = DriverManager.getConnection("jdbc:derby:" + db.getAbsolutePath().replace("\\", "/"));
    try {/*  w  w  w  . ja  va2 s .co  m*/
        Statement stmt = conn.createStatement();
        try {
            ResultSet rs = stmt.executeQuery("select METHOD from MEMBRANE.STATISTIC");
            try {
                Assert.assertTrue(rs.next());
                Assert.assertEquals("GET", rs.getString(1));
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } finally {
        conn.close();
    }

    try {
        DriverManager.getConnection("jdbc:derby:;shutdown=true");
    } catch (SQLException e) {
        // do nothing
    }
}

From source file:Data.java

/**
 * Creates a dataset, consisting of two series of monthly data.
 *
 * @return The dataset./* ww  w. j a  va 2 s . c om*/
 * @throws ClassNotFoundException 
 */
private static XYDataset createDataset(Statement stmt) throws ClassNotFoundException {

    TimeSeries s1 = new TimeSeries("Humidit");
    TimeSeries s2 = new TimeSeries("Temprature");
    ResultSet rs = null;

    try {
        String sqlRequest = "SELECT * FROM `t_temphum`";
        rs = stmt.executeQuery(sqlRequest);
        Double hum;
        Double temp;
        Timestamp date;

        while (rs.next()) {
            hum = rs.getDouble("tmp_humidity");
            temp = rs.getDouble("tmp_temperature");
            date = rs.getTimestamp("tmp_date");

            if (tempUnit == "F") {
                temp = celsiusToFahrenheit(temp.toString());
            }

            if (date != null) {
                s1.add(new Second(date), hum);
                s2.add(new Second(date), temp);
            } else {
                JOptionPane.showMessageDialog(panelPrincipal, "Il manque une date dans la dase de donne",
                        "Date null", JOptionPane.WARNING_MESSAGE);
            }
        }

        rs.close();
    } catch (SQLException e) {
        String exception = e.toString();

        if (e.getErrorCode() == 0) {
            JOptionPane.showMessageDialog(panelPrincipal,
                    "Le serveur met trop de temps  rpondre ! Veuillez rssayer plus tard ou contacter un administrateur",
                    "Connection timed out", JOptionPane.ERROR_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(panelPrincipal, "Voici l'exception : " + exception,
                    "Titre : exception", JOptionPane.ERROR_MESSAGE);
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (Exception e) {
        String exception = e.toString();
        JOptionPane.showMessageDialog(panelPrincipal, "Voici l'exception : " + exception, "Titre : exception",
                JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    }

    // ******************************************************************
    //  More than 150 demo applications are included with the JFreeChart
    //  Developer Guide...for more information, see:
    //
    //  >   http://www.object-refinery.com/jfreechart/guide.html
    //
    // ******************************************************************

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(s1);
    dataset.addSeries(s2);

    return dataset;

}

From source file:com.funambol.json.coredb.dao.DBManager.java

protected void release(Connection connection, Statement stmt, ResultSet rsltSet) {
    if (rsltSet != null)
        try {/* ww  w. ja  va2 s .c  o  m*/
            rsltSet.close();
        } catch (SQLException ex) {
            log.warn("An error occurred closing ResultSet object.", ex);
        }
    if (stmt != null)
        try {
            stmt.close();
            // @todo chiudere la connessione??
        } catch (SQLException ex) {
            log.warn("An error occurred closing ResultSet object.", ex);
        }
    // @todo chiudere la connessione??
}