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:alfio.manager.FileUploadManager.java

public String insertFile(UploadBase64FileModification file) {
    String digest = DigestUtils.sha256Hex(file.getFile());

    if (Integer.valueOf(1).equals(repository.isPresent(digest))) {
        return digest;
    }//from   w  ww .j  a v  a 2s .c o  m

    LobHandler lobHandler = new DefaultLobHandler();

    jdbc.getJdbcOperations().execute(repository.uploadTemplate(),
            new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
                @Override
                protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
                    ps.setString(1, digest);
                    ps.setString(2, file.getName());
                    ps.setLong(3, file.getFile().length);
                    lobCreator.setBlobAsBytes(ps, 4, file.getFile());
                    ps.setString(5, file.getType());
                    ps.setString(6, Json.GSON.toJson(getAttributes(file)));
                }
            });
    return digest;
}

From source file:edu.cmu.lti.oaqa.openqa.hello.eval.passage.PassageMAPEvalPersistenceProvider.java

@Override
public void insertPartialCounts(final Key key, final String sequenceId, final PassageMAPCounts counts)
        throws SQLException {
    final String eName = getClass().getSimpleName();
    String insert = getInsertPassageAggregates();
    final Trace trace = key.getTrace();
    DataStoreImpl.getInstance().jdbcTemplate().update(insert, new PreparedStatementSetter() {
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setString(1, key.getExperiment());
            ps.setString(2, trace.getTrace());
            ps.setString(3, eName);/*from   ww  w .  ja  v a 2s. co m*/
            ps.setFloat(4, counts.getDocavep());
            ps.setFloat(5, counts.getPsgavep());
            ps.setFloat(6, counts.getAspavep());
            ps.setFloat(7, counts.getCount());
            ps.setString(8, sequenceId);
            ps.setInt(9, key.getStage());
            ps.setString(10, trace.getTraceHash());
        }
    });
}

From source file:edu.cmu.lti.oaqa.openqa.hello.eval.passage.PassageMAPEvalPersistenceProvider.java

@Override
public Multimap<Key, PassageMAPCounts> retrievePartialCounts(final ExperimentKey experiment) {
    String select = getSelectPassageAggregates();
    final Multimap<Key, PassageMAPCounts> counts = LinkedHashMultimap.create();
    RowCallbackHandler handler = new RowCallbackHandler() {
        public void processRow(ResultSet rs) throws SQLException {
            Key key = new Key(rs.getString("experimentId"), new Trace(rs.getString("traceId")),
                    rs.getInt("stage"));
            PassageMAPCounts cnt = new PassageMAPCounts(rs.getFloat("docavep"), rs.getFloat("psgavep"),
                    rs.getFloat("aspavep"), rs.getInt("count"));
            counts.put(key, cnt);//from w  w  w  . ja  va2  s.c  om
        }
    };
    DataStoreImpl.getInstance().jdbcTemplate().query(select, new PreparedStatementSetter() {
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setString(1, experiment.getExperiment());
            ps.setInt(2, experiment.getStage());
        }
    }, handler);
    return counts;
}

From source file:com.uiip.gviviani.esercizioweekend.interfaces.impl.DefaultPersonDAO.java

@Override
public boolean inserisciPerson(PersonModel person, String nomeTel) {
    MysqlDataSource datasource = new MysqlDataSource();
    datasource.setUser("root");
    datasource.setPassword("root");
    datasource.setUrl("jdbc:mysql://localhost:3306/Rubrica");
    Connection connection = null;
    try {//w  w w .j  a v  a  2s . c  o m
        connection = datasource.getConnection();
        String sql = "INSERT INTO contatti (nome, cognome, data_nascita, numero, modello) VALUE "
                + "(?, ?, ?, ?, ?);";
        int id;
        String sql2 = "SELECT id FROM telefono WHERE name = ? ;";
        PreparedStatement stat2 = connection.prepareStatement(sql2);
        stat2.setString(1, nomeTel);
        ResultSet res = stat2.executeQuery();
        if (res.first()) {
            id = res.getInt("id");
            PreparedStatement stat = connection.prepareStatement(sql);
            stat.setString(1, person.getNome());
            stat.setString(2, person.getCognome());
            stat.setString(3, person.getData());
            stat.setString(4, person.getNumero());
            stat.setInt(5, id);
            if (stat.executeUpdate() > 0) {
                return true;
            }
        }
    } catch (SQLException e) {
        logger.error(e);
    } finally {
        DbUtils.closeQuietly(connection);
    }
    return false;
}

From source file:minor.register.RegisterAction.java

@Override
public void validate() {
    if (StringUtils.isEmpty(getUname())) {
        addFieldError("uname", "Username cannot be blank.");
    }//  w  ww.  j ava2  s  .  com
    if (StringUtils.isEmpty(getUname())) {
        addFieldError("name", "Name cannot be blank.");
    }
    if (StringUtils.isEmpty(getUname())) {
        addFieldError("password", "Password cannot be blank.");
    }
    if (StringUtils.isEmpty(getCpassword())) {
        addFieldError("cpassword", "Confirm Password cannot be blank.");
    }
    if (StringUtils.isEmpty(getEmail())) {
        addFieldError("email", "Email cannot be blank");
    }
    if (!StringUtils.equals(getPassword(), getCpassword())) {
        addFieldError("cpassword", "Passwords don't match.");
    }
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Minor", "root", "");

        PreparedStatement ps = con.prepareStatement("select * from userinfo where username=?");
        ps.setString(1, uname);

        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            addFieldError("uname", "Username already taken.");
        }
        con.close();
    } catch (ClassNotFoundException e) {
        System.out.println(e);
    } catch (SQLException e) {
        System.out.println(e);
    }
}

From source file:gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCDataElementDAO.java

public boolean isDEDerived(final String deIdSeq) {

    final String qry = "select * from complex_data_elements_view where p_de_idseq = ?";

    JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
    Object result = jdbcTemplate.query(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(qry);
            ps.setString(1, deIdSeq);
            return ps;
        }// w  ww  . j  ava  2s  . c om
    }, new ResultSetExtractor() {
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            if (rs.next()) {
                return new Boolean(true);
            } else {
                return new Boolean(false);
            }
        }
    });
    return (Boolean) result;
}

From source file:com.ywang.alone.handler.task.AuthTask.java

/**
 *  { 'key':'2597aa1d37d432a','uid':'1020293' }
 * /* w w w . j  ava 2 s.  c  o  m*/
 * @param param
 * @return
 */
private static String getUserInfo(String msg) {

    JSONObject jsonObject = AloneUtil.newRetJsonObject();
    JSONObject param = JSON.parseObject(msg);
    String token = param.getString("key");
    String userId = null;

    if (StringUtils.isEmpty(token)) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
        return jsonObject.toJSONString();
    }

    Jedis jedis = JedisUtil.getJedis();
    Long tokenTtl = jedis.ttl("TOKEN:" + token);
    if (tokenTtl == -1) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
    } else {
        userId = jedis.get("TOKEN:" + token);
        LoggerUtil.logMsg("uid is " + userId);
    }

    JedisUtil.returnJedis(jedis);

    if (StringUtils.isEmpty(userId)) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
        return jsonObject.toJSONString();
    }

    String aimUid = param.getString("uid");//uid??
    if (StringUtils.isEmpty(aimUid)) {
        aimUid = userId;
    }
    DruidPooledConnection conn = null;
    PreparedStatement stmt = null;
    JSONObject data = new JSONObject();
    try {
        conn = DataSourceFactory.getInstance().getConn();

        conn.setAutoCommit(false);

        stmt = conn.prepareStatement("SELECT * FROM USERBASE WHERE USER_ID = ?",
                Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, aimUid);

        ResultSet userInfoRs = stmt.executeQuery();
        if (userInfoRs.next()) {
            UserInfo userInfo = new UserInfo();
            userInfo.setRegTime(userInfoRs.getLong("REG_TIME"));
            userInfo.setUserId(userInfoRs.getString("USER_ID"));
            userInfo.setAvatar(userInfoRs.getString("AVATAR"));
            userInfo.setNickName(userInfoRs.getString("NICKNAME"));
            userInfo.setAge(userInfoRs.getString("AGE"));
            userInfo.setHoroscope(userInfoRs.getString("HORO_SCOPE"));
            userInfo.setHeight(userInfoRs.getString("HEIGHT"));
            userInfo.setWeight(userInfoRs.getString("WEIGHT"));
            userInfo.setRoleName(userInfoRs.getString("ROLENAME"));
            userInfo.setAffection(userInfoRs.getString("AFFECTION"));
            userInfo.setPurpose(userInfoRs.getString("PURPOSE"));
            userInfo.setEthnicity(userInfoRs.getString("ETHNICITY"));
            userInfo.setOccupation(userInfoRs.getString("OCCUPATION"));
            userInfo.setLivecity(userInfoRs.getString("LIVECITY"));
            userInfo.setLocation(userInfoRs.getString("LOCATION"));
            userInfo.setTravelcity(userInfoRs.getString("TRAVELCITY"));
            userInfo.setMovie(userInfoRs.getString("MOVIE"));
            userInfo.setMusic(userInfoRs.getString("MUSIC"));
            userInfo.setBooks(userInfoRs.getString("BOOKS"));
            userInfo.setFood(userInfoRs.getString("FOOD"));
            userInfo.setOthers(userInfoRs.getString("OTHERS"));
            userInfo.setIntro(userInfoRs.getString("INTRO"));
            userInfo.setLastLoginTime(userInfoRs.getLong("LAST_LOGIN_TIME"));
            //            userInfo.setMessagePwd(userInfoRs
            //                  .getString("MESSAGE_PWD"));
            userInfo.setMessageUser(userInfoRs.getString("MESSAGE_USER"));
            //         
            userInfo.setOnline("1");

            data.put("userInfo", JSONObject.toJSON(userInfo));

            PreparedStatement pstmt = conn.prepareStatement(
                    "SELECT * FROM uploads WHERE USER_ID = ? and ENABLING=1", Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, aimUid);

            ResultSet pSet = pstmt.executeQuery();
            JSONArray jsonArray = new JSONArray();
            while (pSet.next()) {
                jsonArray.add(pSet.getString("PHOTO_PATH"));
            }
            data.put("photos", JSONObject.toJSON(jsonArray));
            jsonObject.put("data", JSONObject.toJSON(data));

            pSet.close();
            pstmt.close();

        } else {
            jsonObject.put("ret", Constant.RET.SYS_ERR);
            jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR);
            jsonObject.put("errDesc", Constant.ErrorDesc.SYS_ERR);
        }

        userInfoRs.close();
        conn.commit();
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        LoggerUtil.logServerErr(e);
        jsonObject.put("ret", Constant.RET.SYS_ERR);
        jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR);
        jsonObject.put("errDesc", Constant.ErrorDesc.SYS_ERR);
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
            if (null != conn) {
                conn.close();
            }
        } catch (SQLException e) {
            LoggerUtil.logServerErr(e.getMessage());
        }
    }

    return jsonObject.toJSONString();

}

From source file:libepg.util.db.JDBCAccessorTest.java

/**
 * Test of getConnection method, of class JDBCAccessor.
 *
 *//*from   w  w  w.j a  v a 2 s  .c om*/
@Test
public void testGetCon() {
    try {

        LOG.info("getCon");
        JDBCAccessor instance = JDBCAccessor.getInstance();
        String url = "jdbc:sqlite::memory:";
        instance.connect(url);
        java.sql.Connection result = instance.getConnection();
        assertNotNull(result);
        LOG.debug("Connected.");

        Statement stmt = result.createStatement();
        //?
        stmt.executeUpdate("create table test1( name string, age integer )");
        LOG.debug("Made table.");

        //?
        String nameVal = "jjj888???";
        int ageVal = 778;
        String sql1 = "insert into test1 values (?,?)";
        PreparedStatement pstmt1 = result.prepareStatement(sql1);
        pstmt1.setString(1, nameVal);
        pstmt1.setInt(2, ageVal);
        pstmt1.executeUpdate();
        LOG.debug("Inserted.");

        //??
        String sql2 = "select * from test1 where name=? and age=?";
        PreparedStatement pstmt2 = result.prepareStatement(sql2);
        pstmt2.setString(1, nameVal);
        pstmt2.setInt(2, ageVal);
        ResultSet rs = pstmt2.executeQuery();
        while (rs.next()) {
            String str1 = rs.getString("name");
            int int2 = rs.getInt("age");
            System.out.println(str1);
            System.out.println(int2);
            assertEquals(nameVal, str1);
            assertEquals(ageVal, int2);
        }
        LOG.debug("Got data.");

    } catch (SQLException ex) {
        LOG.fatal(ex);
        fail();
    } finally {
        JDBCAccessor.getInstance().close();
    }
}

From source file:com.artivisi.iso8583.persistence.MapperServiceTestIT.java

private void verifyCountDataelement(Mapper m, Connection conn, int count) throws SQLException {
    String sqlSelectDataelement = "select count(*) from iso8583_dataelement where id_mapper = ?";
    PreparedStatement psSelectDataelement = conn.prepareStatement(sqlSelectDataelement);
    psSelectDataelement.setString(1, m.getId());
    ResultSet rsSelectDataelement = psSelectDataelement.executeQuery();
    assertTrue(rsSelectDataelement.next());
    assertEquals(new Integer(count), new Integer(rsSelectDataelement.getInt(1)));
}

From source file:com.ccoe.build.dal.SessionJDBCTemplate.java

public int create(final Session session) {
    final String SQL = "insert into RBT_SESSION (pool_name, machine_name, user_name, environment, "
            + "status, duration, maven_version, goals, start_time, git_url, git_branch, jekins_url, java_version, cause, full_stacktrace, category, filter) "
            + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplateObject.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(SQL, new String[] { "id" });
            ps.setString(1, session.getAppName());
            ps.setString(2, session.getMachineName());
            ps.setString(3, session.getUserName());
            ps.setString(4, session.getEnvironment());
            ps.setString(5, session.getStatus());
            ps.setLong(6, session.getDuration());
            ps.setString(7, session.getMavenVersion());
            ps.setString(8, session.getGoals());
            ps.setTimestamp(9, new java.sql.Timestamp(session.getStartTime().getTime()));
            ps.setString(10, session.getGitUrl());
            ps.setString(11, session.getGitBranch());
            ps.setString(12, session.getJenkinsUrl());
            ps.setString(13, session.getJavaVersion());
            ps.setString(14, getCause(session.getExceptionMessage()));

            setFullStackTraceAsClob(15, ps, session);

            ps.setString(16, session.getCategory());
            ps.setString(17, session.getFilter());

            return ps;
        }/*from  w w w.j  a v a  2  s.  com*/
    }, keyHolder);

    return keyHolder.getKey().intValue();
}