Example usage for java.sql PreparedStatement executeUpdate

List of usage examples for java.sql PreparedStatement executeUpdate

Introduction

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

Prototype

int executeUpdate() throws SQLException;

Source Link

Document

Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.

Usage

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  ww w  .j a  va 2s  .  c om*/
 * @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:las.DBConnector.java

public static void insertMemberIntoTable(Member member) throws SQLException {
    String data = "INSERT INTO MEMBERS(MEMBER_ID,NAME,EMAIL,PRIVILEGE,ISSTAFF)" + "Values (?,?,?,?,?)";
    PreparedStatement pt = conn.prepareStatement(data);
    pt.setInt(1, member.getID());/*  w  ww .j a v  a 2  s .c o  m*/
    pt.setString(2, member.getName());
    pt.setString(3, member.getEmail());
    pt.setString(4, member.getPrivilege());
    pt.setBoolean(5, member.isIsStaff());
    pt.executeUpdate();
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.api.topics.MMXTopicsItemsResourceTest.java

@AfterClass
public static void cleanupDatabase() {
    final String statementStr1 = "DELETE FROM mmxApp WHERE appName LIKE '%" + "mmxtopicstagsresourcetesttopic"
            + "%'";
    final String statementStr2 = "DELETE FROM ofPubsubItem where serviceID = ? AND nodeID = ?";
    Connection conn = null;//from w w w.j  a  va 2 s . com
    PreparedStatement pstmt1 = null;
    PreparedStatement pstmt2 = null;

    try {
        conn = UnitTestDSProvider.getDataSource().getConnection();
        pstmt1 = conn.prepareStatement(statementStr1);
        pstmt1.executeUpdate();
        pstmt2 = conn.prepareStatement(statementStr2);
        pstmt2.setString(1, SERVICE_ID);
        pstmt2.setString(2, getNodeId());
        pstmt2.executeUpdate();

    } catch (SQLException e) {
        LOGGER.error("cleanupDatabase : caught exception cleaning ofPubsubItem");
    } finally {
        CloseUtil.close(LOGGER, pstmt2, conn);
    }
}

From source file:edu.jhu.pha.vospace.oauth.MySQLOAuthProvider2.java

/**
 * Set the access token/*from  ww w  .  ja  v a2 s .  c  o m*/
 * If userId != null, creates link to user's container as root matching the name in consumer. The container should exist already.
 * @param accessor The OAuth accessor object
 * @param userId the owner userId
 * @throws OAuthException
 */
public static synchronized void markAsAuthorized(final Token requestToken, final String userId) {

    try {
        if (null == requestToken.getAttributes().getFirst("root_container")) { // No predefined one (can be predefined for sharing); in this case set the default one
            final String default_root_container = ((Consumer) requestToken.getConsumer()).getAttributes()
                    .getFirst("container");
            if (!UserHelper.userExists(userId)) {
                UserHelper.addDefaultUser(userId);
            }

            //First check if the root node exists
            VospaceId identifier = new VospaceId(new NodePath(default_root_container));
            Node node = NodeFactory.createNode(identifier, userId, NodeType.CONTAINER_NODE);
            logger.debug("Marking as authorized, root node: " + identifier.toString());
            if (!node.isStoredMetadata()) {
                node.setNode(null);
                logger.debug("Creating the node " + node.getUri());
            }

            DbPoolServlet.goSql("Mark oauth token as authorized",
                    "update oauth_accessors set container_id = (select container_id from containers join user_identities on containers.user_id = user_identities.user_id where identity = ? and container_name = ?), authorized = 1 where request_token = ?;",
                    new SqlWorker<Integer>() {
                        @Override
                        public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                            stmt.setString(1, userId);
                            stmt.setString(2, default_root_container);
                            stmt.setString(3, requestToken.getToken());
                            return stmt.executeUpdate();
                        }
                    });
        } else { // the container is already set up (sharing)
            DbPoolServlet.goSql("Mark oauth token as authorized",
                    "update oauth_accessors set authorized = 1 where request_token = ?;",
                    new SqlWorker<Integer>() {
                        @Override
                        public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                            stmt.setString(1, requestToken.getToken());
                            return stmt.executeUpdate();
                        }
                    });
        }
    } catch (URISyntaxException ex) {
        logger.error("Error creating root (app) node for user: " + ex.getMessage());
    }

}

From source file:com.silverpeas.notation.model.RatingDAO.java

public static void createRaterRating(Connection con, RaterRatingPK pk, int note) throws SQLException {
    int newId = 0;
    try {/* w  w w . ja  va 2s  . c o m*/
        newId = DBUtil.getNextId(TABLE_NAME, COLUMN_ID);
    } catch (Exception e) {
        SilverTrace.warn("notation", "RatingDAO.createRaterRating", "root.EX_PK_GENERATION_FAILED", e);
    }

    PreparedStatement prepStmt = con.prepareStatement(QUERY_CREATE_RATER_RATING);
    try {
        prepStmt.setInt(1, newId);
        prepStmt.setString(2, pk.getInstanceId());
        prepStmt.setString(3, pk.getContributionId());
        prepStmt.setString(4, pk.getContributionType());
        prepStmt.setString(5, pk.getRater().getId());
        prepStmt.setInt(6, note);
        prepStmt.executeUpdate();
    } finally {
        DBUtil.close(prepStmt);
    }
}

From source file:com.asakusafw.bulkloader.testutil.UnitTestUtil.java

/**
 * SQL??//from  ww  w .j  a va  2 s .co  m
 * @param sql
 */
public static int executeUpdate(String sql) throws Exception {
    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        printLog("executeUpdate???SQL" + sql, "executeUpdate");
        conn = DBConnection.getConnection();
        stmt = conn.prepareStatement(sql);
        int result = stmt.executeUpdate();
        printLog("executeUpdate?????" + result, "executeUpdate");
        return result;
    } finally {
        DBConnection.closePs(stmt);
        DBConnection.closeConn(conn);
    }
}

From source file:net.codjo.dataprocess.server.treatmenthelper.TreatmentHelper.java

public static void updateDateRepositoryImport(Connection con, String date) throws SQLException {
    PreparedStatement pStmt = con.prepareStatement(
            "delete from PM_DP_CONFIG where CLE = ? " + "insert into PM_DP_CONFIG (CLE, VALEUR) values (?, ?)");
    try {/*from w  w  w  . j av a2s  .c o  m*/
        pStmt.setString(1, DataProcessConstants.KEY_DATE_LAST_IMPORT_REPOSITORY);
        pStmt.setString(2, DataProcessConstants.KEY_DATE_LAST_IMPORT_REPOSITORY);
        pStmt.setString(3, date);
        pStmt.executeUpdate();
    } finally {
        pStmt.close();
    }
}

From source file:edu.jhu.pha.vospace.jobs.JobsProcessor.java

public static void modifyJobState(final JobDescription job, final STATE state, final String note) {

    if (null == job.getEndTime() && (state == STATE.COMPLETED || state == STATE.ERROR)) {
        job.setEndTime(new Date());
    }//from  w  w  w  .j a va 2s. c  om

    job.setState(state);
    final byte[] jobBytes;
    try {
        jobBytes = (new ObjectMapper()).writeValueAsBytes(job);
    } catch (Exception ex) {
        throw new InternalServerErrorException(ex.getMessage());
    }

    DbPoolServlet.goSql("Modify job",
            "update jobs set endtime = ?, state = ?, json_notation = ?, note = ? where id = ?",
            new SqlWorker<Integer>() {
                @Override
                public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                    stmt.setString(1,
                            (null == job.getEndTime()) ? null : dateFormat.format(job.getEndTime().getTime()));
                    stmt.setString(2, job.getState().toString());
                    stmt.setBytes(3, jobBytes);
                    stmt.setString(4, (null == note) ? "" : note);
                    stmt.setString(5, job.getId());
                    return stmt.executeUpdate();
                }
            });
    logger.debug("Job " + job.getId() + " is modified. " + job.getState());
}

From source file:edu.jhu.pha.vospace.oauth.MySQLOAuthProvider2.java

/**
 * Generate a fresh request token and secret for a consumer.
 * //from   w  w  w.j  a  v  a 2  s.  co  m
 * @throws OAuthException
 */
public static synchronized Token generateAccessToken(final Token requestToken, String verifier) {

    // generate oauth_token and oauth_secret
    final String consumer_key = (String) requestToken.getConsumer().getKey();
    // generate token and secret based on consumer_key

    // for now use md5 of name + current time as token
    final String token_data = consumer_key + System.nanoTime();
    final String token = DigestUtils.md5Hex(token_data);
    // first remove the accessor from cache

    int numChanged = DbPoolServlet.goSql("Insert new access token",
            "update oauth_accessors set request_token = NULL, access_token = ?, created = ? where request_token = ? and authorized = 1",
            new SqlWorker<Integer>() {
                @Override
                public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                    stmt.setString(1, token);
                    stmt.setString(2,
                            dateFormat.format(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime()));
                    stmt.setString(3, requestToken.getToken());
                    return stmt.executeUpdate();
                }
            });

    if (numChanged == 0) {
        return null;
    }

    return new Token(token, requestToken.getSecret(), requestToken.getConsumer().getKey(),
            requestToken.getCallbackUrl(), requestToken.getAttributes());
}

From source file:dsd.dao.DAOProvider.java

/**
 * the delete row function done in a secure way
 * /*from w ww.  ja v  a 2 s .c o m*/
 * @param table
 * @param where
 * @param con
 * @return
 * @throws SQLException
 */
public static int DeleteRowSecure(String table, String where, Connection con, Object[] parameters)
        throws SQLException {
    try {
        PreparedStatement command = con.prepareStatement(
                String.format("delete from %s %s", table, (where.trim().equals("") ? "" : "where " + where)));

        if (parameters != null) {
            for (int i = 0; i < parameters.length; i++) {
                SetParameter(command, parameters[i], i + 1);
            }
        }

        return command.executeUpdate();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return 0;
}