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:io.kamax.mxisd.backend.wordpress.WordpressThreePidProvider.java

protected Optional<_MatrixID> find(ThreePid tpid) {
    String query = cfg.getSql().getQuery().getThreepid().get(tpid.getMedium());
    if (Objects.isNull(query)) {
        return Optional.empty();
    }/*from  www.j a  v a2s  .co m*/

    try (Connection conn = wordpress.getConnection()) {
        PreparedStatement stmt = conn.prepareStatement(query);
        stmt.setString(1, tpid.getAddress());

        try (ResultSet rSet = stmt.executeQuery()) {
            while (rSet.next()) {
                String uid = rSet.getString("uid");
                log.info("Found match: {}", uid);
                try {
                    return Optional.of(MatrixID.from(uid, mxCfg.getDomain()).valid());
                } catch (IllegalArgumentException ex) {
                    log.warn("Ignoring match {} - Invalid characters for a Matrix ID", uid);
                }
            }

            log.info("No valid match found in Wordpress");
            return Optional.empty();
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wso2telco.gsma.authenticators.DBUtils.java

public static int readPinAttempts(String sessionId) throws SQLException, AuthenticatorException {

    Connection connection;//from   w  w  w.  j  a  v  a  2  s.c o  m
    PreparedStatement ps;
    int noOfAttempts = 0;
    ResultSet rs;

    String sql = "select attempts from `multiplepasswords` where " + "ussdsessionid=?;";

    connection = getConnectDBConnection();

    ps = connection.prepareStatement(sql);

    ps.setString(1, sessionId);

    rs = ps.executeQuery();

    while (rs.next()) {
        noOfAttempts = rs.getInt("attempts");
    }
    if (connection != null) {
        connection.close();
    }

    return noOfAttempts;
}

From source file:hr.fer.zemris.vhdllab.dao.impl.AbstractOwnedEntityDaoTest.java

private OwnedEntityTable setupOwnedEntity(final String userId, final String name) {
    String query = createInsertStatement("OwnedEntityTable", "id, version, user_id, name", "null, 0, ?, ?");
    getJdbcTemplate().execute(query, new PreparedStatementCallback() {
        @Override/*from  w ww  .j  a  va  2s .  c  o  m*/
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.setString(1, userId);
            ps.setString(2, name);
            return ps.execute();
        }
    });
    return new OwnedEntityTable(userId, name);
}

From source file:oobbit.orm.Categories.java

public boolean isCategory(String id) throws SQLException {
    PreparedStatement statement = getConnection()
            .prepareStatement("SELECT * FROM categories WHERE category_id = ?;");
    statement.setString(1, id);

    ResultSet query = statement.executeQuery();

    return query.next();
}

From source file:org.perconsys.dao.implement.PostDb.java

@Override
public Post create(final Post post) {
    KeyHolder keyh = new GeneratedKeyHolder();
    final String sql = "insert into `posts` (`title`, `content`, `blog_id`, `date`) value (?, ?, ?, now()) ;";

    getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override//  w w  w .jav  a2s. com
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement pstat = conn.prepareStatement(sql, new String[] { "id" });
            pstat.setString(1, post.getTitle());
            pstat.setString(2, post.getContent());
            pstat.setLong(3, post.getBlog().getId());
            return pstat;
        }
    }, keyh);
    Long id = (Long) keyh.getKey();
    post.setId(id);
    return post;
}

From source file:com.surevine.alfresco.audit.repo.JdbcAuditRepository.java

/**
 * Simple write to the database of the audit object.
 * //from   www.  ja  v a2  s  .co  m
 * @see com.surevine.alfresco.audit.AuditRepository#audit(com.surevine.alfresco.audit.Auditable)
 */
public void audit(final Auditable toAudit) {
    this.jdbcTemplate.update(UPDATE_SQL, new PreparedStatementSetter() {

        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setString(1, truncate(toAudit.getUser(), 40));
            ps.setString(2, truncate(toAudit.getAction(), 40));
            ps.setString(3, truncate(toAudit.getSource(), 80));
            ps.setString(4, truncate(toAudit.getSecLabel(), 1024));
            ps.setString(5, truncate(toAudit.getSite(), 80));
            ps.setString(6, truncate(toAudit.getDetails(), 256));
            ps.setString(7, truncate(toAudit.getUrl(), 256));
            ps.setString(8, truncate(toAudit.getVersion(), 10));
            ps.setTimestamp(9, new java.sql.Timestamp(System.currentTimeMillis()));
            ps.setString(10, truncate(toAudit.getRemoteAddress(), 40));
            ps.setString(11, Boolean.toString(toAudit.isSuccess()));
            ps.setString(12, truncate(toAudit.getTags(), 256));
            ps.setString(13, truncate(toAudit.getNodeRef(), 80));
            ps.setLong(14, toAudit.getTimeSpent());
        }
    });
}

From source file:jp.co.golorp.emarf.model.Models.java

/**
 * Model?????IO/*from   w w  w  .  ja v  a  2s  .c o  m*/
 *
 * @param sql
 *            sql
 * @param params
 *            params
 * @return List
 */
private static List<Map<String, Object>> getDatas(final String sql, final Object... params) {

    // ?SQL?
    String rawSql = getRawSql(sql, params);

    // SQL??????
    List<Map<String, Object>> datas = ModelsCache.get(rawSql);
    if (datas != null) {
        return datas;
    }

    // 
    statementLog(rawSql);

    // ?
    PreparedStatement ps = null;
    try {
        ps = Connections.get().prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            ps.setString(i + 1, String.valueOf(params[i]));
        }

        // ??
        datas = new ArrayList<Map<String, Object>>();

        ResultSet rs = null;
        try {

            // ???
            rs = ps.executeQuery();
            while (rs.next()) {

                // ?
                Map<String, Object> data = new LinkedHashMap<String, Object>();

                // ResultSet?META?
                ResultSetMetaData meta = rs.getMetaData();

                // META????
                int columnCount = meta.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {

                    // ???
                    String columnName = meta.getColumnName(i);

                    // ???
                    String propertyName = StringUtil.toCamelCase(columnName);

                    String key = propertyName;
                    if (data.containsKey(propertyName)) {
                        String modelName = StringUtil.toUpperCamelCase(meta.getTableName(i));
                        key = modelName + "." + propertyName;
                    }

                    // 
                    data.put(key, rs.getObject(columnName));
                }

                // 
                datas.add(data);
            }

        } catch (SQLException e) {
            throw new SystemError(e);
        } finally {
            IOUtil.closeQuietly(rs);
        }

    } catch (SQLException e) {
        throw new SystemError(e);
    } finally {
        IOUtil.closeQuietly(ps);
    }

    // SQL?
    // ModelsCache.set(rawSql, datas);

    return datas;
}

From source file:namedatabasescraper.PageScraper.java

public void storeToDb(MainWindow parent) throws SQLException {
    logger.log(Level.INFO, "Started storing names for scraper id {0}", this.dirname);
    Connection conn = NameDatabaseScraper.application.getConnection();
    PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO names VALUES (?, ?)");
    stmt2.setString(2, this.dirname);
    conn.setAutoCommit(false);//from  w  w  w  . jav  a2 s.  c  o m
    for (String name : this.names) {
        stmt2.setString(1, name);
        stmt2.addBatch();
    }
    stmt2.executeBatch();
    conn.setAutoCommit(true);
    logger.log(Level.INFO, "Stored " + this.names.size() + " names for scraper id {0}", this.dirname);
}

From source file:com.javacodegags.waterflooding.model.FloodingImplemented.java

@Override
public int insert(final String name) {
    final String sql = "INSERT INTO flooding (name) VALUES (?);";
    KeyHolder holder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {

        @Override//from   w w  w.  j  a va 2 s . c  om
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, name);
            return ps;
        }
    }, holder);
    return holder.getKey().intValue();
}

From source file:com.sourcesense.ant.dbdep.task.dao.DbDepDao.java

private boolean existDependency(final DependencyDO dependency) {
    Boolean result = new Boolean(false);
    try {//from   w  w w .  j a  v a 2  s  .c om
        result = (Boolean) this.jdbcTemplate.query(psSelect, new PreparedStatementSetter() {
            public void setValues(java.sql.PreparedStatement ps) throws java.sql.SQLException {
                ps.setString(1, dependency.getProject());
                ps.setString(2, dependency.getEnvironment());
                ps.setString(3, dependency.getName());
                ps.setString(4, dependency.getVersion());
            };
        }, new ResultSetExtractor() {
            public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
                if (rs != null && rs.next())
                    return new Boolean(true);
                else
                    return new Boolean(false);
            }
        });
    } catch (DataAccessException e) {
        log.error("Error during checking dependency on this query: " + "" + psSelect + " | dependency: "
                + dependency, e);
        throw new RuntimeException("Error during checking dependency on this query: " + "" + psSelect
                + " | dependency: " + dependency, e);
    }

    return result.booleanValue();
}