Example usage for java.sql PreparedStatement setInt

List of usage examples for java.sql PreparedStatement setInt

Introduction

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

Prototype

void setInt(int parameterIndex, int x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java int value.

Usage

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

/**
 * Deletes just a specific user's rating, and updates the parent table with a proper calculation
 *
 * @param db/*from  ww  w  .j  a v  a 2  s .  c o m*/
 * @param userId
 * @param objectId
 * @param table
 * @param uniqueField
 * @throws SQLException
 */
public static synchronized void delete(Connection db, int userId, int objectId, String table,
        String uniqueField) throws SQLException {
    boolean commit = false;
    try {
        commit = db.getAutoCommit();
        if (commit) {
            db.setAutoCommit(false);
        }

        // Get the project's rating
        int ratingCount = queryObjectRatingCount(db, objectId, table, uniqueField);

        // Get the user's rating
        int thisRating = queryUserRating(db, userId, objectId, table, uniqueField);

        // Delete the user's rating
        PreparedStatement pst = db.prepareStatement(
                "DELETE FROM " + table + "_rating " + "WHERE " + uniqueField + " = ? " + "AND enteredby = ? ");
        pst.setInt(1, objectId);
        pst.setInt(2, userId);
        int deleteCount = pst.executeUpdate();
        pst.close();

        if (deleteCount > 0 && thisRating != INAPPROPRIATE_COMMENT) {
            // Update the parent table's rating information
            // NOTE: make sure not to divide by 0
            pst = db.prepareStatement("UPDATE " + table + " "
                    + "SET rating_count = rating_count - ?, rating_value = rating_value - ?, "
                    + (ratingCount == 0 ? "rating_avg = 0 "
                            : "rating_avg = ((rating_value - ?) / (rating_count - ?)) ")
                    + "WHERE " + uniqueField + " = ? ");
            int i = 0;
            pst.setInt(++i, 1);
            pst.setInt(++i, thisRating);
            if (ratingCount > 1) {
                pst.setInt(++i, thisRating);
                pst.setInt(++i, 1);
            }
            pst.execute();
            pst.close();
        }
    } catch (Exception e) {
        if (commit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
}

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

public static boolean failUpload(int upload_id) {
    PreparedStatement prest = null;
    String sql = "UPDATE `uploads` SET `status`=?,`uploaded`=? WHERE `id`=?";
    try {//  w w w.  jav a 2 s  . c  o m
        prest = c.prepareStatement(sql);
        prest.setString(1, UploadManager.Status.FAILED.toString());
        prest.setInt(3, upload_id);
        boolean res = prest.execute();
        prest.close();
        return res;
    } catch (SQLException e) {
        LOG.error("Error marking upload as failed", e);
        return false;
    }

}

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

public static void insertJsonResponse(int curConsId, TreeMap<Integer, String> input) throws SQLException {
    try {//ww w. j  ava2 s  .co m
        String insertSQL = "INSERT INTO enhancedentities " + "(consultation_id,article_id,json_text) VALUES"
                + "(?,?,?);";
        PreparedStatement prepStatement = connection.prepareStatement(insertSQL);
        //            connection.setAutoCommit(false);
        for (int curArticle : input.keySet()) {
            String json_text = input.get(curArticle);
            prepStatement.setInt(1, curConsId);
            prepStatement.setInt(2, curArticle);
            prepStatement.setString(3, json_text);
            //                prepStatement.executeUpdate();
            prepStatement.addBatch();
        }
        prepStatement.executeBatch();
        //            connection.commit();
        prepStatement.close();

        //            for (int i = 0; i<x.length; i++){
        //                System.out.println(x[i]);
        //            }
    } catch (BatchUpdateException ex) {
        ex.printStackTrace();
        //            System.out.println(ex.getNextException());
    }
}

From source file:com.concursive.connect.web.modules.login.utils.UserUtils.java

private static boolean updateProfileProjectId(Connection db, User user, Project project) throws SQLException {
    PreparedStatement pst = db
            .prepareStatement("UPDATE users " + "SET profile_project_id = ? " + "WHERE user_id = ? ");
    int i = 0;/*from  w ww  .  ja  v a  2 s  .c om*/
    pst.setInt(++i, project.getId());
    pst.setInt(++i, user.getId());
    int count = pst.executeUpdate();
    pst.close();
    // Relate the two objects
    user.setProfileProjectId(project.getId());
    CacheUtils.invalidateValue(Constants.SYSTEM_USER_CACHE, user.getId());
    return count == 1;
}

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  av a 2 s. co  m
    }
    prepStatement.executeBatch();
    prepStatement.close();

}

From source file:com.wso2telco.dep.validator.handler.utils.ValidatorDBUtils.java

/**
 * Method to retrieve the validator class from the database.
 *
 * @param applicationId//from  w  ww.jav a2s  .  c o  m
 * @param apiId
 * @return validator class name
 * @throws ValidatorException
 */
public static String getValidatorClassForSubscription(int applicationId, int apiId) throws ValidatorException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet results = null;
    String sql = "SELECT class FROM validator, subscription_validator "
            + "WHERE subscription_validator.application_id=? AND subscription_validator.api_id=? AND "
            + "validator.id=subscription_validator.validator_id";
    String validatorClass = null;
    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        ps = conn.prepareStatement(sql);
        log.debug("getValidatorClassForSubscription for applicationId---> " + applicationId + " apiId--> "
                + apiId);
        ps.setInt(1, applicationId);
        ps.setInt(2, apiId);
        results = ps.executeQuery();
        if (results.isBeforeFirst()) {
            while (results.next()) {
                validatorClass = results.getString("class");
            }
        } else {
            log.error("Result Set is empty");
        }
    } catch (Exception e) {
        handleException("Error occured while getting Validator Class for App: " + applicationId + " API: "
                + apiId + " from the database", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, results);
    }
    return validatorClass;
}

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

public static Boolean setUploadFinished(int upload_id, Status Status) {
    PreparedStatement prest = null;
    String sql = "UPDATE `uploads` SET `status`=?,`url`=?,`uploaded`=`lenght` WHERE `id`=?";
    try {//from ww  w  . j a v  a  2s . c  o  m
        prest = c.prepareStatement(sql);
        prest.setString(1, Status.toString());
        prest.setString(2, "");
        prest.setInt(3, upload_id);
        boolean res = prest.execute();
        prest.close();
        return res;
    } catch (SQLException e) {
        LOG.error("Error marking upload as finished", e);
        return false;
    }
}

From source file:com.flexive.core.LifeCycleInfoImpl.java

/**
 * Update a tables LifeCycleInfo//from   w  w  w.  ja  va2  s . c  om
 *
 * @param table         table that contains the lifecycle
 * @param idField       field containing the id
 * @param id            the id to update
 * @param verField      field containing the id (optional)
 * @param ver           the version to update (optional)
 * @param updateCreated update created by/at as well?
 * @param throwOnNone   throw an exception if no rows were updated?
 * @throws FxUpdateException if a database field could not be updated
 */
public static void updateLifeCycleInfo(String table, String idField, String verField, long id, int ver,
        boolean updateCreated, boolean throwOnNone) throws FxUpdateException {
    final UserTicket ticket = FxContext.getUserTicket();

    Connection con = null;
    PreparedStatement stmt = null;

    try {
        con = Database.getDbConnection();
        stmt = con.prepareStatement("UPDATE " + table + " SET MODIFIED_BY=?, MODIFIED_AT=?"
                + (updateCreated ? ", CREATED_BY=?, CREATED_AT=?" : "") + " WHERE " + idField + "=?"
                + (verField != null && ver > 0 ? " AND " + verField + "=?" : ""));
        final long now = System.currentTimeMillis();
        stmt.setInt(1, (int) ticket.getUserId());
        stmt.setLong(2, now);
        if (updateCreated) {
            stmt.setInt(3, (int) ticket.getUserId());
            stmt.setLong(4, now);
            stmt.setLong(5, id);
        } else
            stmt.setLong(3, id);
        if (verField != null && ver > 0)
            stmt.setInt((updateCreated ? 6 : 4), ver);
        int iCnt = stmt.executeUpdate();
        if (iCnt != 1 && throwOnNone)
            throw new FxUpdateException("Updating LifeCycleInfo failed. " + iCnt + " rows were updated!");
    } catch (SQLException se) {
        throw new FxUpdateException(LOG, se.getMessage(), se);
    } finally {
        Database.closeObjects(LifeCycleInfoImpl.class, con, stmt);
    }
}

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

public static Boolean updateTemplate(int id, Template template) throws SQLException, IOException {
    PreparedStatement prest = null;
    ObjectMapper mapper = new ObjectMapper();
    String sql = "UPDATE `templates` SET `data`=? WHERE `id`=?";
    prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    prest.setString(1, mapper.writeValueAsString(template));
    prest.setInt(2, id);
    boolean res = prest.execute();
    prest.close();/*w  w w .j a  v  a2 s . co  m*/
    return res;
}

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

public static Boolean startUpload(int id, long progress) {
    PreparedStatement prest = null;
    String sql = "UPDATE `uploads` SET `status`=?,`uploaded`=? WHERE `id`=?";
    try {/* w  w w. j a  v  a2 s  .  c o  m*/
        prest = c.prepareStatement(sql);
        prest.setString(1, UploadManager.Status.UPLOADING.toString());
        prest.setLong(2, progress);
        prest.setInt(3, id);
        boolean res = prest.execute();
        prest.close();
        return res;
    } catch (SQLException e) {
        LOG.error("Error starting upload", e);
        return false;
    }
}