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:ke.co.tawi.babblesms.server.persistence.contacts.PhoneDAO.java

/**
 * @see ke.co.tawi.babblesms.server.persistence.contacts.BabblePhoneDAO#getPhones(java.lang.String, ke.co.tawi.babblesms.server.beans.contact.Contact)
 *//*  ww  w.  j av a2 s  . c  o  m*/
@Override
public List<Phone> getPhones(String phoneNum) {

    List<Phone> phoneList = new ArrayList<>();

    try (Connection conn = dbCredentials.getConnection();
            PreparedStatement psmt = conn
                    .prepareStatement("SELECT * FROM phone WHERE phonenumber ILIKE ? LIMIT 30;");) {

        psmt.setString(1, "%" + phoneNum + "%");

        ResultSet rset = psmt.executeQuery();

        phoneList = beanProcessor.toBeanList(rset, Phone.class);

        rset.close();

    } catch (SQLException e) {
        logger.error("SQL Exception when getting phones that match the " + " string: " + phoneNum);
        logger.error(ExceptionUtils.getStackTrace(e));
    }

    return phoneList;
}

From source file:Accounts.java

private void loadAccounts() {
    Vector v = new Vector();
    try {/*from  w  ww  .j a v a  2s  . c  o m*/
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("SELECT acc_id FROM acc_acc");

        while (rs.next()) {
            v.addElement(rs.getString("acc_id"));
        }
        rs.close();
    } catch (SQLException e) {
        displaySQLErrors(e);
    }
    accountNumberList.setListData(v);
}

From source file:ca.phon.ipadictionary.impl.DatabaseDictionary.java

@Override
public String[] lookup(String ortho) throws IPADictionaryExecption {
    Connection conn = IPADatabaseManager.getInstance().getConnection();
    List<String> retVal = new ArrayList<String>();

    if (conn != null) {
        ortho = StringUtils.strip(ortho, "?!\"'.\\/@&$()^%#*");
        String qSt = "SELECT * FROM transcript WHERE orthography = ? AND langId = ?";
        try {/*from   w ww.j a  va  2 s  .co m*/
            PreparedStatement pSt = conn.prepareStatement(qSt);
            pSt.setString(1, ortho.toLowerCase());
            pSt.setString(2, getLanguage().toString());

            java.sql.ResultSet rs = pSt.executeQuery();
            while (rs.next()) {
                retVal.add(rs.getString("IPA"));
            }
            rs.close();
            pSt.close();
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }

    return retVal.toArray(new String[0]);
}

From source file:com.l2jfree.gameserver.datatables.CharNameTable.java

private CharNameTable() {
    Connection con = null;//w  w w .  j a  v  a 2s . c  o m
    try {
        con = L2DatabaseFactory.getInstance().getConnection();

        PreparedStatement statement = con
                .prepareStatement("SELECT charId, account_name, char_name FROM characters");
        ResultSet rset = statement.executeQuery();

        while (rset.next())
            update(rset.getInt("charId"), rset.getString("account_name"), rset.getString("char_name"));

        rset.close();
        statement.close();
    } catch (SQLException e) {
        _log.warn("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    _log.info("CharNameTable: Loaded " + _mapByObjectId.size() + " character names.");
}

From source file:com.alibaba.druid.benckmark.pool.CaseKylin_mysql.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();//from   w  w w. j a va2s.c  o  m

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        PreparedStatement stmt = conn.prepareStatement("SELECT 1 FROM DUAL");
                        ResultSet rs = stmt.executeQuery();
                        rs.next();
                        rs.getInt(1);
                        rs.close();
                        stmt.close();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

From source file:com.alibaba.druid.benckmark.pool.Oracle_Case3.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();/* w w w .jav  a  2  s.c o  m*/

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery("SELECT 1 FROM DUAL");
                        rs.next();
                        // Assert.isTrue(!rs.isClosed());
                        rs.close();
                        // Assert.isTrue(!stmt.isClosed());
                        stmt.close();
                        Assert.isTrue(stmt.isClosed());
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

From source file:com.reydentx.core.client.MySQLClient.java

public void close(java.sql.ResultSet rs) {
    try {//  ww  w.j  av a  2 s.  co m
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
    } catch (Exception ex) {
        _logger.error(ex.getMessage(), ex);
    }
}

From source file:com.chaosinmotion.securechat.server.commands.DropMessages.java

public static void processRequest(UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    ArrayList<Message> messages = new ArrayList<Message>();

    JSONArray a = requestParams.getJSONArray("messages");
    int i, len = a.length();
    for (i = 0; i < len; ++i) {
        JSONObject item = a.getJSONObject(i);
        Message msg = new Message();
        msg.message = item.getInt("messageid");
        msg.checksum = item.getString("checksum");
        messages.add(msg);/* w ww .  ja v a2  s  .c  om*/
    }

    /*
     * Iterate through the messages, deleting each. We only delete a
     * message if message belongs to the user and the checksum matches.
     * This assumes it's our message and it was read with someone who
     * can read the message.
     * 
     * (Thus, the weird query)
     */

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        int count = 0;
        c = Database.get();
        ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN "
                + "    (SELECT Messages.messageid " + "     FROM Messages, Devices "
                + "     WHERE Messages.messageid = ? " + "     AND Messages.checksum = ? "
                + "     AND Devices.deviceid = Messages.deviceid " + "     AND Devices.userid = ?)");

        for (Message msg : messages) {
            /*
             * Get the device ID for this device. Verify it belongs to the
             * user specified
             */

            ps.setInt(1, msg.message);
            ps.setString(2, msg.checksum);
            ps.setInt(3, userinfo.getUserID());
            ps.addBatch();
            ++count;
            if (count > 10240) {
                ps.executeBatch();
            }
        }
        if (count > 0) {
            ps.executeBatch();
        }
    } catch (BatchUpdateException batch) {
        throw batch.getNextException();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:com.oic.event.RegisterProfile.java

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;/*w  ww .jav a 2  s .c  o  m*/
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "INSERT INTO user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ?, secretkey = ?";
        ps = con.prepareStatement(sql);
        ps.setString(1, json.get("studentid").toString());
        ps.setString(2, json.get("username").toString());
        ps.setInt(3, Integer.parseInt(json.get("avatarid").toString()));
        ps.setInt(4, Integer.parseInt(json.get("grade").toString()));
        ps.setInt(5, Integer.parseInt(json.get("gender").toString()));
        ps.setDate(6, toDate(json.get("birthday").toString()));
        ps.setString(7, json.get("comment").toString());
        ps.setString(8, json.get("secretkey").toString());
        ps.executeUpdate();
        ps.close();

        sql = "SELECT last_insert_id() AS last";
        ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (!rs.next()) {
            throw new SQLException();
        }
        long userid = rs.getLong("last");
        rs.close();
        ps.close();

        sql = "INSERT INTO setting SET userid = ?, privategrade = ?, privatesex = ?, privatebirth = ?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, userid);
        ps.setInt(2, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(4, Integer.parseInt(json.get("vbirthday").toString()));
        ps.executeUpdate();
        ps.close();
        con.commit();

        responseJSON.put("status", 0);
        webSocket.userNoLogin();
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException sq) {
            LOG.warning("[setProfile]Error Rolling back.");
        }
        e.printStackTrace();
        responseJSON.put("status", 1);
    } finally {
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(SetProfile.class.getName()).log(Level.WARNING,
                    "Error going back to AutoCommit mode", ex);
        }
    }
    webSocket.sendJson(responseJSON);
}

From source file:adept.kbapi.sql.QuickJDBC.java

/**
 * execute query to check if object exists in the database. This closes the
 * prepared statement passed in/*from w w  w. j  av a 2  s . c o m*/
 */
public boolean recordExists(PreparedStatement preparedStmt) throws SQLException {
    boolean doesRecordExist = false;
    java.sql.ResultSet rs = null;
    try {
        rs = preparedStmt.executeQuery();
        doesRecordExist = rs.next();
    } finally {
        try {
            if (rs != null)
                rs.close();
        } catch (Exception e) {
        }
        ;
        try {
            if (preparedStmt != null)
                preparedStmt.close();
        } catch (Exception e) {
        }
        ;
    }
    return doesRecordExist;
}