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:com.firewallid.util.FISQL.java

public static String getFirstFieldInsertIfNotExist(Connection conn, String tableName, String field,
        Map<String, String> fields) throws SQLException {
    /* Query *///from w  ww .  j  ava  2  s  .c o  m
    String query = "SELECT " + field + " FROM " + tableName + " WHERE "
            + Joiner.on(" = ? AND ").join(fields.keySet()) + " = ?";

    /* Execute */
    PreparedStatement pst = conn.prepareStatement(query);
    int i = 1;
    for (String value : fields.values()) {
        pst.setString(i, value);
        i++;
    }
    ResultSet executeQuery = pst.executeQuery();
    if (executeQuery.next()) {
        return executeQuery.getString(field);
    }

    /* Row is not exists. Insert */
    query = "INSERT INTO " + tableName + " (" + Joiner.on(", ").join(fields.keySet()) + ") VALUES ("
            + StringUtils.repeat("?, ", fields.size() - 1) + "?)";
    pst = conn.prepareStatement(query);
    i = 1;
    for (String value : fields.values()) {
        pst.setString(i, value);
        i++;
    }
    if (pst.execute()) {
        return null;
    }
    return getFirstFieldInsertIfNotExist(conn, tableName, field, fields);
}

From source file:com.l2jfree.gameserver.model.GMAudit.java

public static void auditGMAction(String gm_name, String target, String type, String action, String param) {
    if (Config.GM_AUDIT) {
        Connection con = null;/*from   w ww.  j a  va  2s.  co  m*/
        try {
            con = L2DatabaseFactory.getInstance().getConnection(con);
            PreparedStatement statement = con.prepareStatement(
                    "INSERT INTO gm_audit(gm_name, target, type, action, param, date) VALUES(?,?,?,?,?,now())");

            statement.setString(1, gm_name);
            statement.setString(2, target);
            statement.setString(3, type);
            statement.setString(4, action);
            statement.setString(5, param);

            statement.executeUpdate();
        } catch (Exception e) {
            _log.fatal("", e);
        } finally {
            L2DatabaseFactory.close(con);
        }
    }
}

From source file:de.thejeterlp.bukkit.login.SQLAccount.java

protected static void updateAccount(Account a) throws SQLException {
    checkReflection();/*from www  .  jav a  2  s  . c o m*/
    Validate.notNull(a, "a cannot be null!");

    PreparedStatement st = Login.getInstance().getDB().getPreparedStatement(
            "UPDATE `" + Statics.PASSWORD_TABLE + "` SET `password` = ? WHERE `userID` = ?;");
    st.setString(1, a.getPassword());
    st.setInt(2, a.getID());
    st.executeUpdate();
    Login.getInstance().getDB().closeStatement(st);
}

From source file:de.thejeterlp.bukkit.login.SQLAccount.java

protected static Account convert(UUID uuid) throws SQLException {
    checkReflection();/*from   w  w w.j  a va2s  .  c  om*/
    Validate.notNull(uuid, "uuid cannot be null!");
    PreparedStatement st = Login.getInstance().getDB()
            .getPreparedStatement("SELECT * FROM `" + Statics.USER_TABLE + "` WHERE `uuid` = ? LIMIT 1;");
    st.setString(1, uuid.toString());
    ResultSet rs = st.executeQuery();
    while (rs.next()) {
        int id = rs.getInt("id");
        Login.getInstance().getDB().closeResultSet(rs);
        Login.getInstance().getDB().closeStatement(st);
        PreparedStatement sta = Login.getInstance().getDB().getPreparedStatement(
                "SELECT * FROM `" + Statics.PASSWORD_TABLE + "` WHERE `userID` = ? LIMIT 1;");
        sta.setInt(1, id);
        ResultSet rset = sta.executeQuery();
        while (rset.next()) {
            String hash = rset.getString("password");
            Login.getInstance().getDB().closeResultSet(rset);
            Login.getInstance().getDB().closeStatement(sta);
            return new Account(id, uuid, hash);
        }
    }
    return null;
}

From source file:com.us.test.H2Helper.java

public static void laodData2H2Db(File ips, String url, String uname, String upasswd)
        throws IOException, SQLException {
    List<String> ipsegma = FileUtils.readLines(ips, "GBK");

    JdbcConnectionPool cp = JdbcConnectionPool.create(url, uname, upasswd);
    Connection conn = cp.getConnection();
    String sql = "insert into ips values(?,?,?,?,?,?)";
    int i = 0;/*from   ww  w  .  ja va  2 s .c  om*/
    for (String ip : ipsegma) {
        PreparedStatement statement = conn.prepareStatement(sql);
        String[] ipary = ip.split("\\s+");
        if (ipary.length < 2 || ipary[0].indexOf(".") < 0)
            continue;
        statement.setString(1, ip2Long(ipary[0].trim()));
        statement.setString(2, ip2Long(ipary[1].trim()));
        statement.setString(3, ipary[1].trim());
        statement.setString(4, ipary[1].trim());
        statement.setString(5, ipary.length <= 2 ? "" : ipary[2].trim());
        statement.setString(6, ipary.length <= 3 ? "" : ipary[3].trim());
        System.out.println(i++ + ":" + statement.execute());

    }
    conn.close();
    cp.dispose();
}

From source file:com.firewallid.util.FISQL.java

public static void updateRowInsertIfNotExist(Connection conn, String tableName,
        Map<String, String> updateConditions, Map<String, String> fields) throws SQLException {
    /* Query *//*from   w  w w.  j a v  a2  s.co m*/
    String query = "SELECT " + Joiner.on(", ").join(updateConditions.keySet()) + " FROM " + tableName
            + " WHERE " + Joiner.on(" = ? AND ").join(updateConditions.keySet()) + " = ?";

    /* Execute */
    PreparedStatement pst = conn.prepareStatement(query);
    int i = 1;
    for (String value : updateConditions.values()) {
        pst.setString(i, value);
        i++;
    }
    ResultSet executeQuery = pst.executeQuery();
    if (executeQuery.next()) {
        /* Update */
        query = "UPDATE " + tableName + " SET " + Joiner.on(" = ?, ").join(fields.keySet()) + " = ? WHERE "
                + Joiner.on(" = ? AND ").join(updateConditions.keySet()) + " = ?";
        pst = conn.prepareStatement(query);
        i = 1;
        for (String value : fields.values()) {
            pst.setString(i, value);
            i++;
        }
        for (String value : updateConditions.values()) {
            pst.setString(i, value);
            i++;
        }
        pst.executeUpdate();
        return;
    }

    /* Row is not exists. Insert */
    query = "INSERT INTO " + tableName + " (" + Joiner.on(", ").join(fields.keySet()) + ", "
            + Joiner.on(", ").join(updateConditions.keySet()) + ") VALUES ("
            + StringUtils.repeat("?, ", fields.size() + updateConditions.size() - 1) + "?)";
    pst = conn.prepareStatement(query);
    i = 1;
    for (String value : fields.values()) {
        pst.setString(i, value);
        i++;
    }
    for (String value : updateConditions.values()) {
        pst.setString(i, value);
        i++;
    }
    pst.execute();
}

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());
    }/*w ww . ja  v  a  2 s  . c o  m*/

    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:de.is24.infrastructure.gridfs.http.metadata.generation.PrimaryDbGenerator.java

private static int fillStatementForYumPackageFormatEntry(final PreparedStatement ps,
        final YumPackageFormatEntry dependency, int counter) throws SQLException {
    ps.setString(counter++, dependency.getName());
    if (dependency.getFlags() == null) {
        ps.setString(counter++, null);/*  w w  w .  ja  v  a2s .co  m*/
        ps.setString(counter++, null);
        ps.setString(counter++, null);
        ps.setString(counter++, null);
    } else {
        ps.setString(counter++, dependency.getFlags());
        ps.setInt(counter++, dependency.getVersion().getEpoch());
        ps.setString(counter++, nullIfBlank(dependency.getVersion().getVer()));
        ps.setString(counter++, nullIfBlank(dependency.getVersion().getRel()));
    }
    return counter;
}

From source file:net.big_oh.common.jdbc.JdbcProxyExerciser.java

private static void exercisePreparedBatchInsert(Connection con) throws SQLException {
    logger.info(StringUtils.center("exercise prepared batch insert", 100, "-"));

    PreparedStatement preparedStmnt = null;
    try {//from  w w w.java  2 s  .co  m
        preparedStmnt = con.prepareStatement("INSERT INTO TEST_TABLE VALUES ( ? )");
        preparedStmnt.setString(1, "value4");
        preparedStmnt.addBatch();
        preparedStmnt.setString(1, "value5");
        preparedStmnt.addBatch();
        preparedStmnt.executeBatch();
    } finally {
        DbUtils.closeQuietly(preparedStmnt);
    }
}

From source file:com.concursive.connect.web.modules.activity.utils.ProjectHistoryUtils.java

public static int findNextThreadPosition(Connection db, ProjectHistory parentProjectHistory)
        throws SQLException {
    int count = 0;
    PreparedStatement pst = db
            .prepareStatement("SELECT count(*) AS ccount " + "FROM project_history " + "WHERE lineage LIKE ? ");
    pst.setString(1, parentProjectHistory.getLineage() + parentProjectHistory.getId() + "/%");
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        count = rs.getInt("ccount");
    }//from   w  ww. j  a  v  a2 s  .  c  o  m
    rs.close();
    pst.close();
    return (parentProjectHistory.getThreadPosition() + count + 1);
}