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:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Procedure to avoid an explicit insert yourself.
 *//*from   ww  w  .ja  v  a 2s. co m*/
public static void addRepo(String repoUrl) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    String query = "INSERT INTO localdb.sys_network.repositories (repo_url) " + "VALUES (?)";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1, repoUrl);
    ps.execute();
    ps.close();
}

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

/**
 * Does the delete for you./*  ww  w  .ja  v a2 s.  c o m*/
 */
public static void removeRepo(String repoUrl) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    String query = "DELETE FROM localdb.sys_network.repositories WHERE " + "repo_url = ?";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1, repoUrl);
    ps.execute();
    ps.close();
}

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//from  w  ww .j  ava  2 s  .  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:com.wso2telco.dbUtil.DataBaseConnectUtils.java

/**
 * Close PreparedStatement//from  w w  w . j a  v  a2s  .com
 *
 * @param preparedStatement PreparedStatement
 */
private static void closeStatement(PreparedStatement preparedStatement) {
    if (preparedStatement != null) {
        try {
            preparedStatement.close();
        } catch (SQLException e) {
            log.error("Database error. Could not close PreparedStatement. Continuing with others. - "
                    + e.getMessage(), e);
        }
    }
}

From source file:com.jmstoolkit.pipeline.plugin.XMLValueTransformerTest.java

/**
 * Starts an embedded Derby database, creates the lookup table and
 * inserts one row for the test. Also creates the source and expected
 * result XML documents. Finally, initializes the XMLValueTransformer.
 * /*from   w ww.java 2 s .c o  m*/
 * @throws Exception on JDBC problems
 */
@BeforeClass
public static void setUpClass() throws Exception {
    // loads the "driver" which apparently means the database is running
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
    PreparedStatement ps;
    //Connection connection = DriverManager.getConnection("jdbc:derby:XDB;create=true");     

    EmbeddedDataSource40 dataSource = new EmbeddedDataSource40();
    dataSource.setCreateDatabase("create");
    dataSource.setDatabaseName(DB_NAME);
    Connection connection = dataSource.getConnection();
    ps = connection.prepareStatement(SQL_CREATE_TABLE);
    ps.execute();
    ps = connection.prepareStatement(SQL_INSERT_ROW);
    ps.execute();
    ps.close();
    // Create the transformer
    XFORM = new XMLValueTransformer(dataSource);
    XFORM.setSql(SQL_SELECT);
    XFORM.setSrcPath("/trade/currency");

    // Create the XML SOURCE document
    SOURCE = DocumentHelper.createDocument();
    Element root = SOURCE.addElement("trade");
    root.addElement("currency").addText("XXX");
    // create the expected result document for comparison
    RESULT = DocumentHelper.createDocument();
    root = RESULT.addElement("trade");
    root.addElement("currency").addText("USD");
}

From source file:com.flexive.core.security.FxDBAuthentication.java

/**
 * Increase the number of failed login attempts for the given user
 *
 * @param con    an open and valid connection
 * @param userId user id/*from   w  w w . j ava2s  .c  o m*/
 * @throws SQLException on errors
 */
private static void increaseFailedLoginAttempts(Connection con, long userId) throws SQLException {
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement(
                "UPDATE " + TBL_ACCOUNT_DETAILS + " SET FAILED_ATTEMPTS=FAILED_ATTEMPTS+1 WHERE ID=?");
        ps.setLong(1, userId);
        if (ps.executeUpdate() == 0) {
            ps.close();
            ps = con.prepareStatement("INSERT INTO " + TBL_ACCOUNT_DETAILS
                    + " (ID,APPLICATION,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC) "
                    + "VALUES (?,?,?,?,?,?,?)");
            ps.setLong(1, userId);
            ps.setString(2, FxContext.get().getApplicationId());
            ps.setBoolean(3, false);
            ps.setLong(4, System.currentTimeMillis());
            ps.setString(5, FxContext.get().getRemoteHost());
            ps.setLong(6, 1); //one failed attempt
            ps.setString(7, AuthenticationSource.Database.name());
            ps.executeUpdate();
        }
    } finally {
        if (ps != null)
            ps.close();
    }
}

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

/**
 * Just installs the jar by file name, default in sys_network schema.
 *///www  .  ja va 2s.c o m
public static void installJar(String jarFile) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    String name = jarFile.replaceAll("\\.jar", "");
    String query = "CREATE or REPLACE JAR localdb.sys_network.\"" + name + "\"\n"
            + "LIBRARY 'file:${FARRAGO_HOME}/plugin/" + jarFile + "'\n" + "OPTIONS(1)";
    PreparedStatement ps = conn.prepareStatement("set schema 'localdb.sys_network'");
    ps.execute();
    ps = conn.prepareStatement(query);
    ps.execute();
    ps.close();
}

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

public static void deletePlaylist(int id) {
    PreparedStatement prest = null;
    String sql = "DELETE FROM `playlists` WHERE `id`=?";
    try {/*from   www . java 2s .  c  om*/
        prest = c.prepareStatement(sql);
        prest.setInt(1, id);
        prest.close();
    } catch (SQLException e) {
        LOG.error("Error deleting Playlist ", e);
    }

}

From source file:at.becast.youploader.account.Account.java

public static Account read(String name) throws IOException {
    PreparedStatement stmt;
    try {/*from w  ww  . j a  v a  2  s. co m*/
        stmt = c.prepareStatement("SELECT * FROM `accounts` WHERE `name`=? LIMIT 1");
        stmt.setString(1, name);
        ResultSet rs = stmt.executeQuery();
        ObjectMapper mapper = new ObjectMapper();
        List<Cookie> c = mapper.readValue(rs.getString("cookie"), new TypeReference<List<Cookie>>() {
        });
        int id = rs.getInt("id");
        String token = rs.getString("refresh_token");
        stmt.close();
        rs.close();
        return new Account(id, name, token, c);
    } catch (SQLException e) {
        LOG.error("Account read error!", e);
        return null;
    }
}

From source file:com.concursive.connect.web.modules.common.social.rating.dao.Rating.java

/**
 * Deletes references from the specified table when the object is being deleted
 *
 * @param db/*w  w w  .  j av  a 2s.co m*/
 * @param objectId
 * @param table
 * @param uniqueField
 * @throws SQLException
 */
public static void delete(Connection db, int objectId, String table, String uniqueField) throws SQLException {
    PreparedStatement pst = db
            .prepareStatement("DELETE FROM " + table + "_rating " + "WHERE " + uniqueField + " = ? ");
    pst.setInt(1, objectId);
    pst.execute();
    pst.close();
}