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:at.becast.youploader.database.SQLite.java

public static int saveTemplate(Template template) throws SQLException, IOException {
    PreparedStatement prest = null;
    ObjectMapper mapper = new ObjectMapper();
    String sql = "INSERT INTO `templates` (`name`, `data`) " + "VALUES (?,?)";
    prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    prest.setString(1, template.getName());
    prest.setString(2, mapper.writeValueAsString(template));
    prest.execute();/*from w  w  w . j  av a  2  s  . c o m*/
    ResultSet rs = prest.getGeneratedKeys();
    prest.close();
    if (rs.next()) {
        int id = rs.getInt(1);
        rs.close();
        return id;
    } else {
        return -1;
    }
}

From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java

/**
 * Close ResultSet//from ww w . ja v  a  2 s  . c  om
 *
 * @param resultSet ResultSet
 */
private static void closeResultSet(ResultSet resultSet) {
    if (resultSet != null) {
        try {
            resultSet.close();
        } catch (SQLException e) {
            log.error("Database error. Could not close ResultSet  - " + e.getMessage(), e);
        }
    }
}

From source file:com.autentia.tnt.version.Version.java

public static Version getDatabaseVersion(Connection con) throws SQLException {
    Statement stmt = null;//from  w  w  w.  j  a  va 2  s. c o  m
    ResultSet rs = null;
    String ret = null;

    try {
        stmt = con.createStatement();
        rs = stmt.executeQuery("select version from Version");

        if (rs.next()) {
            ret = rs.getString("version");
        }
    } catch (SQLException e) {
        throw e;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("Error al liberar el resultset", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.error("Error al liberar el statement", e);
            }
        }
    }

    return new Version(ret == null ? "0" : ret);
}

From source file:com.concursive.connect.web.webdav.WebdavManager.java

public static int validateUser(Connection db, HttpServletRequest req) throws Exception {
    String argHeader = req.getHeader("Authorization");
    HashMap params = getAuthenticationParams(argHeader);
    String username = (String) params.get("username");

    if (md5Helper == null) {
        md5Helper = MessageDigest.getInstance("MD5");
    }// w w w  .j  a  va 2  s . c  o m

    int userId = -1;
    String password = null;
    PreparedStatement pst = db.prepareStatement(
            "SELECT user_id, webdav_password " + "FROM users " + "WHERE username = ? " + "AND enabled = ? ");
    pst.setString(1, username);
    pst.setBoolean(2, true);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        userId = rs.getInt("user_id");
        password = rs.getString("webdav_password");
    }
    rs.close();
    pst.close();
    if (userId == -1) {
        return userId;
    }
    String method = req.getMethod();
    String uri = (String) params.get("uri");
    String a2 = MD5Encoder.encode(md5Helper.digest((method + ":" + uri).getBytes()));
    String digest = MD5Encoder
            .encode(md5Helper.digest((password + ":" + params.get("nonce") + ":" + a2).getBytes()));
    if (!digest.equals(params.get("response"))) {
        userId = -1;
    }
    return userId;
}

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

/**
 * Process a forgot password request. This generates a token that the
 * client is expected to return with the change password request.
 * @param requestParams/*  w  w  w  .j  av  a2s .  c o  m*/
 * @throws SQLException 
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws JSONException 
 * @throws NoSuchAlgorithmException 
 */

public static void processRequest(JSONObject requestParams)
        throws SQLException, ClassNotFoundException, IOException, NoSuchAlgorithmException, JSONException {
    String username = requestParams.optString("username");

    /*
     * Step 1: Convert username to the userid for this
     */
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    int userID = 0;
    String retryID = UUID.randomUUID().toString();

    try {
        c = Database.get();
        ps = c.prepareStatement("SELECT userid " + "FROM Users " + "WHERE username = ?");
        ps.setString(1, username);
        rs = ps.executeQuery();
        if (rs.next()) {
            userID = rs.getInt(1);
        }

        if (userID == 0)
            return;
        ps.close();
        rs.close();

        /*
         * Step 2: Generate the retry token and insert into the forgot 
         * database with an expiration date 1 hour from now.
         */

        Timestamp ts = new Timestamp(System.currentTimeMillis() + 3600000);
        ps = c.prepareStatement("INSERT INTO ForgotPassword " + "    ( userid, token, expires ) " + "VALUES "
                + "    ( ?, ?, ?)");
        ps.setInt(1, userID);
        ps.setString(2, retryID);
        ps.setTimestamp(3, ts);
        ps.execute();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }

    /*
     * Step 3: formulate a JSON string with the retry and send
     * to the user. The format of the command we send is:
     * 
     * { "cmd": "forgotpassword", "token": token }
     */

    JSONObject obj = new JSONObject();
    obj.put("cmd", "forgotpassword");
    obj.put("token", retryID);
    MessageQueue.getInstance().enqueueAdmin(userID, obj.toString(4));
}

From source file:at.becast.youploader.database.SQLite.java

public static int addUpload(File file, Video data, VideoMetadata metadata, Date startAt)
        throws SQLException, IOException {
    PreparedStatement prest = null;
    ObjectMapper mapper = new ObjectMapper();
    String sql = "INSERT INTO `uploads` (`account`, `file`, `lenght`, `data`,`enddir`, `metadata`, `status`,`starttime`) "
            + "VALUES (?,?,?,?,?,?,?,?)";
    prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    prest.setInt(1, metadata.getAccount());
    prest.setString(2, file.getAbsolutePath());
    prest.setLong(3, file.length());//from w w  w  .j a  v  a 2 s.  c o m
    prest.setString(4, mapper.writeValueAsString(data));
    prest.setString(5, metadata.getEndDirectory());
    prest.setString(6, mapper.writeValueAsString(metadata));
    prest.setString(7, UploadManager.Status.NOT_STARTED.toString());
    if (startAt == null) {
        prest.setString(8, "");
    } else {
        prest.setDate(8, new java.sql.Date(startAt.getTime()));
    }
    prest.execute();
    ResultSet rs = prest.getGeneratedKeys();
    prest.close();
    if (rs.next()) {
        int id = rs.getInt(1);
        rs.close();
        return id;
    } else {
        return -1;
    }
}

From source file:com.concursive.connect.web.modules.setup.utils.SetupUtils.java

/**
 * Determines if there is an administrative user configured in the database
 *
 * @param db/*from w  w w  .  j  a  v  a  2  s. c  o m*/
 * @return
 */
public static boolean isAdminInstalled(Connection db) {
    int count = -1;
    try {
        PreparedStatement pst = db.prepareStatement(
                "SELECT count(*) AS recordcount " + "FROM users " + "WHERE access_admin = ? ");
        pst.setBoolean(1, true);
        ResultSet rs = pst.executeQuery();
        rs.next();
        count = rs.getInt("recordcount");
        rs.close();
        pst.close();
    } catch (Exception e) {
    }
    return count > 0;
}

From source file:com.concursive.connect.web.modules.setup.utils.SetupUtils.java

/**
 * Determines if a default project has been installed
 *
 * @param db//from  w  w w  .jav a2  s .com
 * @return
 */
public static boolean isDefaultProjectInstalled(Connection db) {
    int count = -1;
    try {
        PreparedStatement pst = db.prepareStatement(
                "SELECT count(*) AS recordcount " + "FROM projects " + "WHERE system_default = ? ");
        pst.setBoolean(1, true);
        ResultSet rs = pst.executeQuery();
        rs.next();
        count = rs.getInt("recordcount");
        rs.close();
        pst.close();
    } catch (Exception e) {
    }
    return count > 0;
}

From source file:act.installer.brenda.SQLConnection.java

/**
 * A handy function that closes a result set when an iterator has hit the end.  Does some ugly stuff with exceptions
 * but needs to be used inside an iterator.
 * @param results The result set to check for another row.
 * @param stmt A statement to close when we're out of results.
 * @return True if the result set has more rows, false otherwise (after closing).
 *///from ww  w . j  av  a2 s  . com
private static boolean hasNextHelper(ResultSet results, Statement stmt) {
    try {
        // TODO: is there a better way to do this?
        if (results.isLast()) {
            results.close(); // Tidy up if we find we're at the end.
            stmt.close();
            return false;
        } else {
            return true;
        }
    } catch (SQLException e) {
        /* Note: this is usually not a great thing to do.  In this circumstance we don't expect the
         * calling code to do anything but crash anyway, so... */
        throw new RuntimeException(e);
    }
}

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

/**
 * Return the list of device identifiers associated with this account.
 * @param userinfo//from  w ww .j  a v a  2s  .c o  m
 * @param requestParams
 * @return
 * @throws IOException 
 * @throws SQLException 
 * @throws ClassNotFoundException 
 */
public static ReturnResult processRequest(Login.UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    String username = requestParams.getString("username");

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

    try {
        c = Database.get();

        /*
         *    Get user ID
         */

        ps = c.prepareStatement("SELECT userid " + "FROM Users " + "WHERE username = ?");
        ps.setString(1, username);
        rs = ps.executeQuery();

        int userid = 0;
        if (rs.next()) {
            userid = rs.getInt(1);
        } else {
            return new ReturnResult(Errors.ERROR_UNKNOWNUSER, "Unknown user");
        }
        rs.close();
        rs = null;
        ps.close();
        ps = null;

        /*
         * Get devices
         */
        ps = c.prepareStatement("SELECT Devices.deviceuuid, Devices.publickey " + "FROM Devices, Users "
                + "WHERE Users.userid = Devices.userid " + "AND Users.username = ?");
        ps.setString(1, username);
        rs = ps.executeQuery();

        DeviceReturnResult drr = new DeviceReturnResult(userid);
        while (rs.next()) {
            drr.addDeviceUUID(rs.getString(1), rs.getString(2));
        }
        return drr;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}