Example usage for java.sql PreparedStatement close

List of usage examples for java.sql PreparedStatement close

Introduction

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

Prototype

void close() throws SQLException;

Source Link

Document

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

Usage

From source file:module.entities.NameFinder.DB.java

public static void InsertJsonLemmas(TreeMap<EntityEntry, Integer> docEntities, int text_id, int jsonKey)
        throws SQLException {
    String insertSQL = "INSERT INTO json_annotated_lemmas "
            + "(lemma_text,lemma_category,lemma_text_id,lemma_jsonKey,lemma_count) VALUES" + "(?,?,?,?,?)";
    PreparedStatement prepStatement = connection.prepareStatement(insertSQL);
    for (Map.Entry<EntityEntry, Integer> ent : docEntities.entrySet()) {

        prepStatement.setString(1, ent.getKey().text);
        prepStatement.setString(2, ent.getKey().category);
        prepStatement.setInt(3, text_id);
        prepStatement.setInt(4, jsonKey);
        prepStatement.setInt(5, ent.getValue().intValue());
        prepStatement.addBatch();//from   w  w w .  j a  v  a  2 s.c om
    }
    prepStatement.executeBatch();
    prepStatement.close();

}

From source file:com.concursive.connect.web.modules.profile.utils.ProjectUtils.java

public static int retrieveWebcastIdFromProjectId(Connection db, int projectId) throws SQLException {
    int webcastId = -1;
    PreparedStatement pst = db
            .prepareStatement("SELECT webcast_id " + "FROM project_webcast " + "WHERE project_id = ? ");
    pst.setInt(1, projectId);/*w w w .java  2 s. c  o m*/
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        webcastId = rs.getInt("webcast_id");
    }
    rs.close();
    pst.close();

    return webcastId;
}

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Grabbing the list of repos along with their availability
 * status for internal use. /*from  ww w  . j  a v  a 2s  .co  m*/
 */
private static List<RepoInfo> getRepoUrls() throws SQLException {
    List<RepoInfo> repos = new ArrayList<RepoInfo>();

    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    String query = "SELECT repo_url FROM localdb.sys_network.repositories " + "ORDER BY repo_url";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.execute();
    ResultSet rs = ps.getResultSet();
    while (rs.next()) {
        String repo = rs.getString(1);
        boolean accessible = true;
        try {
            JSONObject ob = downloadMetadata(repo);
        } catch (SQLException e) {
            if (e.getMessage().equals(URL_TIMEOUT))
                accessible = false;
        }
        repos.add(new RepoInfo(repo, accessible));
    }
    rs.close();
    ps.close();

    return repos;
}

From source file:com.dynamobi.ws.util.DB.java

@SuppressWarnings(value = { "unchecked" })
public static <T extends DBLoader> void execute(String query, T obj, List<T> list) {
    Connection conn = null;/*from  w  w w.  java2 s.c  om*/
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        conn = getConnection();
        ps = conn.prepareStatement(query);
        ps.setMaxRows(0);
        if (ps.execute()) {
            rs = ps.getResultSet();
        }

        while (rs != null && rs.next()) {
            obj.loadRow(rs);
            if (list != null) {
                list.add((T) obj.copy());
            }
        }
        obj.finalize();
    } catch (SQLException ex) {
        obj.exception(ex);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (conn != null) {
            releaseConnection();
        }
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException ex1) {
            ex1.printStackTrace();
        }
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex3) {
            ex3.printStackTrace();
        }
    }
}

From source file:database.HashTablesTools.java

private static int enterInPDBfilesHashDB(Connection connexion, String hash, String fourLetterCode,
        String tableName, char[] chainType, char[] chainName, String sequence) {
    try {//from  w  w  w  .  j ava  2s  . c om
        String insertTableSQL = "INSERT INTO " + tableName + " "
                + "(pdbfilehash, fourLettercode, chainId, chainType, sequenceString) VALUES" + "(?,?,?,?,?)";
        PreparedStatement preparedStatement = connexion.prepareStatement(insertTableSQL);
        preparedStatement.setString(1, hash);
        preparedStatement.setString(2, String.valueOf(fourLetterCode));
        preparedStatement.setString(3, String.valueOf(chainName));
        preparedStatement.setString(4, String.valueOf(chainType));
        preparedStatement.setString(5, sequence);

        int ok = preparedStatement.executeUpdate();
        preparedStatement.close();
        System.out.println(ok + " raw created " + String.valueOf(fourLetterCode) + "  "
                + String.valueOf(chainName) + "  " + String.valueOf(chainType)); // + " " + sequence);
        return 1;
    } catch (SQLException e1) {
        System.out.println("Failed to enter entry in " + tableName + " table ");
        return 0;
    }
}

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

public static void insertPlaylist(Item item, int account) throws SQLException, IOException {
    PreparedStatement prest = null;
    String sql = "INSERT INTO `playlists` (`name`, `playlistid`,`image`,`account`,`shown`) "
            + "VALUES (?,?,?,?,1)";
    prest = c.prepareStatement(sql);/*from   w  ww. j  ava  2  s  . c o  m*/
    prest.setString(1, item.snippet.title);
    prest.setString(2, item.id);
    URL url = new URL(item.snippet.thumbnails.default__.url);
    InputStream is = null;
    is = url.openStream();
    byte[] imageBytes = IOUtils.toByteArray(is);
    prest.setBytes(3, imageBytes);
    prest.setInt(4, account);
    prest.execute();
    prest.close();
}

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

/**
 * Process the create account request. This should receive the following
 * objects: the username, the password, the device ID and the public key
 * for the device. This adds a new entry in the account database, and
 * creates a new device.//from w w w .  ja  v  a2  s .co m
 * 
 * If the user account cannot be created, this returns nil.
 * @param requestParams
 * @return
 */
public static UserInfo processRequest(JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    String username = requestParams.optString("username");
    String password = requestParams.optString("password");
    String deviceid = requestParams.optString("deviceid");
    String pubkey = requestParams.optString("pubkey");

    /*
     * Attempt to insert a new user into the database
     */

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

    try {
        c = Database.get();
        ps = c.prepareStatement("INSERT INTO Users " + "    ( username, password ) " + "VALUES "
                + "    ( ?, ? ); SELECT currval('Users_userid_seq')");
        ps.setString(1, username);
        ps.setString(2, password);

        try {
            ps.execute();
        } catch (SQLException ex) {
            return null; // Can't insert; duplicate username?
        }
        int utc = ps.getUpdateCount();
        int userid = 0;
        if ((utc == 1) && ps.getMoreResults()) {
            rs = ps.getResultSet();
            if (rs.next()) {
                userid = rs.getInt(1);
            }
            rs.close();
            rs = null;
        }

        ps.close();
        ps = null;

        /*
         * We now have the user index. Insert the device. Note that it is
         * highly unlikely we will have a UUID collision, but we verify
         * we don't by deleting any rows in the device table with the
         * specified UUID. The worse case scenario is a collision which
         * knocks someone else off the air. (The alternative would be
         * to accidentally send the wrong person duplicate messages.)
         * 
         * Note that we don't actually use a device-identifying identifer,
         * choosing instead to pick a UUID, so we need to deal with
         * the possibility (however remote) of duplicate UUIDs.
         * 
         * In the off chance we did have a collision, we also delete all
         * old messages to the device; that prevents messages from being
         * accidentally delivered.
         */

        ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN "
                + "    (SELECT Messages.messageid " + "     FROM Messages, Devices "
                + "     WHERE Messages.deviceid = Devices.deviceid " + "     AND Devices.deviceuuid = ?)");
        ps.setString(1, deviceid);
        ps.execute();
        ps.close();
        ps = null;

        ps = c.prepareStatement("DELETE FROM Devices WHERE deviceuuid = ?");
        ps.setString(1, deviceid);
        ps.execute();
        ps.close();
        ps = null;

        ps = c.prepareStatement("INSERT INTO Devices " + "    ( userid, deviceuuid, publickey ) " + "VALUES "
                + "    ( ?, ?, ?)");
        ps.setInt(1, userid);
        ps.setString(2, deviceid);
        ps.setString(3, pubkey);
        ps.execute();

        /*
         * Complete; return the user info record
         */

        return new Login.UserInfo(userid);
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:com.concursive.connect.web.modules.profile.utils.ProjectUtils.java

/**
 * Accepts a project for the given user/*  ww  w. ja v a  2 s  . c om*/
 *
 * @param db        Description of the Parameter
 * @param projectId Description of the Parameter
 * @param userId    Description of the Parameter
 * @throws SQLException Description of the Exception
 */
public static void accept(Connection db, int projectId, int userId) throws SQLException {
    PreparedStatement pst = db.prepareStatement("UPDATE project_team " + "SET status = ? "
            + "WHERE project_id = ? " + "AND user_id = ? " + "AND status = ? ");
    DatabaseUtils.setInt(pst, 1, TeamMember.STATUS_ADDED);
    pst.setInt(2, projectId);
    pst.setInt(3, userId);
    pst.setInt(4, TeamMember.STATUS_PENDING);
    pst.executeUpdate();
    pst.close();
    CacheUtils.invalidateValue(Constants.SYSTEM_PROJECT_CACHE, projectId);
}

From source file:com.wso2.raspberrypi.Util.java

public static String getValue(String key) {
    String value = null;//from w w  w  . j  av  a  2s  .co  m
    BasicDataSource ds = getBasicDataSource();

    Connection dbConnection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    try {
        dbConnection = ds.getConnection();
        prepStmt = dbConnection.prepareStatement("SELECT * FROM KV_PAIR WHERE k='" + key + "'");
        rs = prepStmt.executeQuery();

        while (rs.next()) {
            value = rs.getString("v");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (dbConnection != null) {
                dbConnection.close();
            }
            if (prepStmt != null) {
                prepStmt.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return value;
}

From source file:org.red5.server.plugin.admin.dao.UserDAO.java

public static boolean addUser(String username, String hashedPassword) {
    boolean result = false;

    Connection conn = null;/*  w w w  .j  a  v  a 2s  . c o m*/
    PreparedStatement stmt = null;
    try {
        // JDBC stuff
        DataSource ds = UserDatabase.getDataSource();

        conn = ds.getConnection();
        //make a statement
        stmt = conn
                .prepareStatement("INSERT INTO APPUSER (username, password, enabled) VALUES (?, ?, 'enabled')");
        stmt.setString(1, username);
        stmt.setString(2, hashedPassword);
        log.debug("Add user: {}", stmt.execute());
        //add role
        stmt = conn.prepareStatement("INSERT INTO APPROLE (username, authority) VALUES (?, 'ROLE_SUPERVISOR')");
        stmt.setString(1, username);
        log.debug("Add role: {}", stmt.execute());
        //
        result = true;
    } catch (Exception e) {
        log.error("Error connecting to db", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
    return result;
}