Example usage for java.sql PreparedStatement setString

List of usage examples for java.sql PreparedStatement setString

Introduction

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

Prototype

void setString(int parameterIndex, String x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java String value.

Usage

From source file:ca.qc.adinfo.rouge.mail.db.MailDb.java

public static boolean sendMail(DBManager dbManager, long fromId, long toId, RougeObject content) {

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;/* w w w  . j  a  v  a2 s  .  com*/
    String sql = null;

    sql = "INSERT INTO rouge_mail (`from`, `to`, `content`, `status`, `time_sent`) " + "VALUES (?, ?, ?, ?, ?)";

    try {
        connection = dbManager.getConnection();
        stmt = connection.prepareStatement(sql);

        stmt.setLong(1, fromId);
        stmt.setLong(2, toId);
        stmt.setString(3, content.toJSON().toString());
        stmt.setString(4, "unr");
        stmt.setTimestamp(5, new Timestamp(System.currentTimeMillis()));

        int ret = stmt.executeUpdate();

        return (ret > 0);

    } catch (SQLException e) {
        log.error(stmt);
        log.error(e);
        return false;

    } finally {

        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:ca.qc.adinfo.rouge.achievement.db.AchievementDb.java

public static boolean updateAchievement(DBManager dbManager, String key, long userId, double progress) {

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;// w  w  w .  j ava  2s. c  o m
    String sql = null;

    sql = "INSERT INTO rouge_achievement_progress (`achievement_key`, `user_id`, `progress`) "
            + "VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE progress = GREATEST(progress, ?)";

    try {
        connection = dbManager.getConnection();
        stmt = connection.prepareStatement(sql);

        stmt.setString(1, key);
        stmt.setLong(2, userId);
        stmt.setDouble(3, progress);
        stmt.setDouble(4, progress);

        int ret = stmt.executeUpdate();

        return (ret > 0);

    } catch (SQLException e) {
        log.error(stmt);
        log.error(e);
        return false;

    } finally {

        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.oracle.tutorial.jdbc.StoredProcedureJavaDBSample.java

public static void raisePrice(String coffeeName, double maximumPercentage, BigDecimal[] newPrice)
        throws SQLException {

    Connection con = DriverManager.getConnection("jdbc:default:connection");
    PreparedStatement pstmt = null;
    ResultSet rs = null;/* w  w w .  j av a  2s.  co  m*/
    BigDecimal oldPrice;

    String queryGetCurrentCoffeePrice = "select COFFEES.PRICE " + "from COFFEES "
            + "where COFFEES.COF_NAME = ?";

    pstmt = con.prepareStatement(queryGetCurrentCoffeePrice);
    pstmt.setString(1, coffeeName);
    rs = pstmt.executeQuery();

    if (rs.next()) {
        oldPrice = rs.getBigDecimal(1);
    } else {
        return;
    }

    BigDecimal maximumNewPrice = oldPrice.multiply(new BigDecimal(1 + maximumPercentage));

    // Test if newPrice[0] > maximumNewPrice

    if (newPrice[0].compareTo(maximumNewPrice) == 1) {
        newPrice[0] = maximumNewPrice;
    }

    // Test if newPrice[0] <= oldPrice

    if (newPrice[0].compareTo(oldPrice) < 1) {
        newPrice[0] = oldPrice;
        return;
    }

    String queryUpdatePrice = "update COFFEES " + "set COFFEES.PRICE = ? " + "where COFFEES.COF_NAME = ?";

    pstmt = con.prepareStatement(queryUpdatePrice);
    pstmt.setBigDecimal(1, newPrice[0]);
    pstmt.setString(2, coffeeName);
    pstmt.executeUpdate();
}

From source file:FacultyAdvisement.StudentRepository.java

public static void adminUpdate(DataSource ds, Student student, String oldUsername) throws SQLException {
    Connection conn = ds.getConnection();
    if (conn == null) {
        throw new SQLException("conn is null; Can't get db connection");
    }/*from w  w  w  . j a  v a2 s  . c om*/
    try {

        PreparedStatement ps;
        ps = conn.prepareStatement(
                "Update STUDENT set EMAIL=?, FIRSTNAME=?, LASTNAME=?, MAJORCODE=?, PHONE=?, ADVISED=? where STUID=?");
        ps.setString(1, student.getUsername());
        ps.setString(2, student.getFirstName());
        ps.setString(3, student.getLastName());
        ps.setString(4, student.getMajorCode());
        ps.setString(5, student.getPhoneNumber());
        if (student.isAdvised()) {
            ps.setString(6, "true");
        } else {
            ps.setString(6, "false");
        }
        ps.setString(7, student.getId());
        ps.executeUpdate();

        ps = conn.prepareStatement("Update USERTABLE set USERNAME=? where USERNAME=?");
        ps.setString(1, student.getUsername());
        ps.setString(2, oldUsername);
        ps.executeUpdate();

        ps = conn.prepareStatement("Update GROUPTABLE set USERNAME=? where USERNAME=?");
        ps.setString(1, student.getUsername());
        ps.setString(2, oldUsername);
        ps.executeUpdate();

        if (student.isResetPassword()) {
            String newPassword = UUID.randomUUID().toString();
            String encryptedPassword = SHA256Encrypt.encrypt(newPassword);
            ps = conn.prepareStatement("Update USERTABLE set PASSWORD=? where USERNAME=?");
            ps.setString(1, encryptedPassword);
            ps.setString(2, student.getUsername());
            ps.executeUpdate();

            Email email = new HtmlEmail();
            email.setHostName("smtp.googlemail.com");
            email.setSmtpPort(465);
            email.setAuthenticator(new DefaultAuthenticator("uco.faculty.advisement", "!@#$1234"));
            email.setSSLOnConnect(true);
            email.setFrom("uco.faculty.advisement@gmail.com");
            email.setSubject("UCO Faculty Advisement Password Change");
            email.setMsg("<font size=\"3\">An admin has resetted your password, your new password is \""
                    + newPassword + "\"." + "\n<p align=\"center\">UCO Faculty Advisement</p></font>");
            email.addTo(student.getUsername());
            email.send();

        }

    } catch (EmailException ex) {
        Logger.getLogger(StudentRepository.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        conn.close();
    }

    //students = (HashMap<String, StudentPOJO>) readAll(); // reload the updated info
}

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");
    }//from w ww .j  a v a  2s  .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.tethrnet.manage.db.UserDB.java

/**
 * inserts new user/*from w  w w .  j a  va2s .  com*/
 * 
 * @param con DB connection 
 * @param user user object
 */
public static Long insertUser(Connection con, User user) {

    Long userId = null;

    try {
        PreparedStatement stmt = con.prepareStatement(
                "insert into users (email, username, auth_type, user_type, password, salt) values (?,?,?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, user.getEmail());
        stmt.setString(2, user.getUsername());
        stmt.setString(3, user.getAuthType());
        stmt.setString(4, user.getUserType());
        if (StringUtils.isNotEmpty(user.getPassword())) {
            String salt = EncryptionUtil.generateSalt();
            stmt.setString(5, EncryptionUtil.hash(user.getPassword() + salt));
            stmt.setString(6, salt);
        } else {
            stmt.setString(5, null);
            stmt.setString(6, null);
        }
        stmt.execute();
        ResultSet rs = stmt.getGeneratedKeys();
        if (rs != null && rs.next()) {
            userId = rs.getLong(1);
        }
        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }

    return userId;

}

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

public static void setPlaylistHidden(int id, String hidden) throws SQLException {
    PreparedStatement prest = null;
    String sql = "UPDATE `playlists` SET `shown`=? WHERE `id`=?";
    prest = c.prepareStatement(sql);//from  w ww  .  j  a v  a 2  s.  co  m
    prest.setString(1, hidden);
    prest.setInt(2, id);
    prest.execute();
    prest.close();
}

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

public static void InsertLexiconEntry(PreparedStatement statement, String lexiconType, String lemma,
        String entity, String lang) throws SQLException {
    try {//from ww w . j  a va 2 s  . c  o  m
        statement.setString(1, lexiconType);
        statement.setString(2, lemma);
        statement.setString(3, entity);
        statement.setString(4, lang);
        statement.addBatch();
        batchSize++;
        if (batchSize == 1000) {
            statement.executeBatch();
            statement.clearBatch();
            batchSize = 0;
        }
    } catch (SQLException ex) {
        System.err.println("Skipping:" + lemma + " " + entity + " " + ex.getMessage());
    }
}

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();/* w ww . ja v  a  2 s  .  c  om*/
    }
    prepStatement.executeBatch();
    prepStatement.close();

}

From source file:edu.ucsd.library.xdre.web.StatsCollectionsReportController.java

public static long getDiskSize(String collectionId) throws SQLException {
    Connection con = null;//from  w w w  .  ja va  2 s. c o  m
    PreparedStatement ps = null;
    ResultSet rs = null;
    long size = 0;
    try {
        con = Constants.DAMS_DATA_SOURCE.getConnection();
        ps = con.prepareStatement(StatsUsage.DLP_COLLECTION_RECORD_QUERY);
        ps.setString(1, collectionId);
        rs = ps.executeQuery();
        if (rs.next()) {
            size = rs.getLong("SIZE_BYTES");
        }
    } finally {
        Statistics.close(rs);
        Statistics.close(ps);
        Statistics.close(con);
        rs = null;
        ps = null;
        con = null;
    }
    return size;
}