Example usage for java.sql PreparedStatement setLong

List of usage examples for java.sql PreparedStatement setLong

Introduction

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

Prototype

void setLong(int parameterIndex, long x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java long value.

Usage

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public List<Penalty> findByPlayerAndType(Long player, Integer type) {
    String sql = "select * from penalty where playerid = ? and type = ? order by created desc";
    Connection conn = null;/*from   ww w .  jav  a  2s.com*/
    List<Penalty> list = new ArrayList<Penalty>();
    try {
        conn = ConnectionFactory.getSecondaryConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setLong(1, player);
        st.setInt(2, type.intValue());
        ResultSet rs = st.executeQuery();
        while (rs.next()) {
            Penalty penalty = new Penalty();
            loadPenalty(penalty, rs);
            list.add(penalty);
        }
    } catch (SQLException e) {
        logger.error("findByPlayerAndType: {}", e);
    } catch (IOException e) {
        logger.error("findByPlayerAndType: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return list;
}

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public Penalty findLastActivePenalty(Long player, Integer type) {
    String sql = "select * from penalty where playerid = ? and type = ? and active = ? order by updated desc limit 1";
    Connection conn = null;/*from  w  ww .  j  av  a2 s.  c  o m*/
    Penalty penalty = null;
    try {
        conn = ConnectionFactory.getSecondaryConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setLong(1, player);
        st.setInt(2, type.intValue());
        st.setBoolean(3, true);
        ResultSet rs = st.executeQuery();
        if (rs.next()) {
            penalty = new Penalty();
            loadPenalty(penalty, rs);
        }
    } catch (SQLException e) {
        logger.error("findByPlayerAndTypeAndActive: {}", e);
    } catch (IOException e) {
        logger.error("findByPlayerAndTypeAndActive: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return penalty;
}

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public List<Penalty> findByPlayerAndTypeAndActive(Long player, Integer type) {
    String sql = "select * from penalty where playerid = ? and type = ? and active = ? order by created desc";
    Connection conn = null;//from w ww  .j  a  va  2s  . c  o  m
    List<Penalty> list = new ArrayList<Penalty>();
    try {
        conn = ConnectionFactory.getSecondaryConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setLong(1, player);
        st.setInt(2, type.intValue());
        st.setBoolean(3, true);
        ResultSet rs = st.executeQuery();
        while (rs.next()) {
            Penalty penalty = new Penalty();
            loadPenalty(penalty, rs);
            list.add(penalty);
        }
    } catch (SQLException e) {
        logger.error("findByPlayerAndTypeAndActive: {}", e);
    } catch (IOException e) {
        logger.error("findByPlayerAndTypeAndActive: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return list;
}

From source file:com.splicemachine.mrio.api.core.SMSQLUtil.java

public long getChildTransactionID(Connection conn, long parentTxsID, String tableName) throws SQLException {
    PreparedStatement ps = null;
    ResultSet rs = null;//w w w.j av  a  2s  . c  o m
    long childTxsID;
    try {
        ps = conn.prepareStatement("call SYSCS_UTIL.SYSCS_START_CHILD_TRANSACTION(?,?)");
        ps.setLong(1, parentTxsID);
        ps.setString(2, tableName);
        ResultSet rs3 = ps.executeQuery();
        rs3.next();
        childTxsID = rs3.getLong(1);
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
    }
    return childTxsID;
}

From source file:com.flexive.ejb.beans.HistoryTrackerEngineBean.java

/**
 * {@inheritDoc}//from   ww w  . jav a 2  s  . c o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public void track(Long mandator, String typeName, String loginname, String application, String session,
        String remoteHost, String message, String data, String key, Object... args) {
    Connection con = null;
    PreparedStatement ps = null;
    try {
        final UserTicket ticket = FxContext.getUserTicket();
        con = Database.getDbConnection();
        boolean hasMandator = mandator != null;
        ps = con.prepareStatement(
                StorageManager.escapeReservedWords(hasMandator ? HISTORY_INSERT_MANDATOR : HISTORY_INSERT));
        ps.setLong(1, ticket.getUserId());
        ps.setString(2, StringUtils.isBlank(loginname) ? ticket.getLoginName() : loginname);

        ps.setLong(3, System.currentTimeMillis());
        ps.setString(4, key);
        StorageManager.setBigString(ps, 5, StringUtils.join(args, '|'));
        try {
            if (StringUtils.isNotBlank(message))
                ps.setString(6, message);
            else
                ps.setString(6,
                        FxSharedUtils.getLocalizedMessage("History", FxLanguage.ENGLISH, "en", key, args));
        } catch (Exception e) {
            ps.setString(6, key);
        }
        FxContext si = FxContext.get();
        ps.setString(7, StringUtils.isNotBlank(session) ? session
                : (si.getSessionId() == null ? "<unknown>" : si.getSessionId()));
        ps.setString(8, StringUtils.isNotBlank(application) ? application
                : (si.getApplicationId() == null ? "<unknown>" : si.getApplicationId()));
        ps.setString(9, StringUtils.isNotBlank(remoteHost) ? remoteHost
                : (si.getRemoteHost() == null ? "<unknown>" : si.getRemoteHost()));
        if (StringUtils.isNotBlank(typeName)) {
            ps.setNull(10, java.sql.Types.NUMERIC);
            ps.setString(11, typeName);
        } else {
            ps.setNull(10, java.sql.Types.NUMERIC);
            ps.setNull(11, java.sql.Types.VARCHAR);
        }
        ps.setNull(12, java.sql.Types.NUMERIC);
        ps.setNull(13, java.sql.Types.NUMERIC);
        if (StringUtils.isNotBlank(data))
            StorageManager.setBigString(ps, 14, data);
        else
            ps.setNull(14, java.sql.Types.VARCHAR);
        if (hasMandator)
            ps.setLong(15, mandator);
        ps.executeUpdate();
    } catch (Exception ex) {
        LOG.error(ex.getMessage());
    } finally {
        Database.closeObjects(HistoryTrackerEngineBean.class, con, ps);
    }
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

@Test
public void testObjectTimestamp() throws Exception {
    Statement stmt = con.createStatement();
    java.util.Date now = new java.util.Date();

    // Create the target Column family
    //String createCF = "CREATE COLUMNFAMILY t74 (id BIGINT PRIMARY KEY, col1 TIMESTAMP)";        
    String createCF = "CREATE COLUMNFAMILY t74 (id BIGINT PRIMARY KEY, col1 TIMESTAMP)";

    stmt.execute(createCF);//from   www  .j  av  a2  s  .co  m
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));

    Statement statement = con.createStatement();

    String insert = "INSERT INTO t74 (id, col1) VALUES (?, ?);";

    PreparedStatement pstatement = con.prepareStatement(insert);
    pstatement.setLong(1, 1L);
    pstatement.setObject(2, new Timestamp(now.getTime()), Types.TIMESTAMP);
    pstatement.execute();

    ResultSet result = statement.executeQuery("SELECT * FROM t74;");

    assertTrue(result.next());
    assertEquals(1L, result.getLong(1));

    // try reading Timestamp directly
    Timestamp stamp = result.getTimestamp(2);
    assertEquals(now, stamp);

    // try reading Timestamp as an object
    stamp = result.getObject(2, Timestamp.class);
    assertEquals(now, stamp);

    System.out.println(resultToDisplay(result, 74, "current date"));

}

From source file:com.surfs.storage.common.datasource.jdbc.JdbcDao.java

@Override
public Object insert(String poolName, String sql, Object... params) throws Exception {
    Connection conn = null;/*from  w w w.j  a  v  a 2s . c om*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = getConnection(poolName);
        ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        for (int i = 0; i < params.length; i++) {
            if (params[i] instanceof String)
                ps.setString(i + 1, (String) params[i]);
            else if (params[i] instanceof Integer)
                ps.setInt(i + 1, (Integer) params[i]);
            else if (params[i] instanceof Long)
                ps.setLong(i + 1, (Long) params[i]);
            else if (params[i] instanceof Timestamp)
                ps.setTimestamp(i + 1, (Timestamp) params[i]);
        }
        ps.execute();
        rs = ps.getGeneratedKeys();
        if (rs.next())
            return rs.getObject(1);
        return null;
    } catch (Exception e) {
        throw e;
    } finally {
        JdbcUtils.closeResultset(rs);
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnect(conn);
    }
}

From source file:net.mindengine.oculus.frontend.service.runs.JdbcTestRunDAO.java

@Override
public Long createTestRunParameter(Long testRunId, String name, String value, boolean isInput)
        throws Exception {
    PreparedStatement ps = getConnection().prepareStatement(
            "insert into test_run_parameters (test_run_id, name, value, type) values (?,?,?,?)");

    ps.setLong(1, testRunId);
    ps.setString(2, name);//from   ww w.  j a v a2 s  . c  o  m
    ps.setString(3, value);
    if (isInput) {
        ps.setString(4, "input");
    } else
        ps.setString(4, "output");

    logger.info(ps);
    ps.execute();

    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        return rs.getLong(1);
    }

    return null;
}

From source file:com.buckwa.dao.impl.excise4.Form23DaoImpl.java

@Override
public void create(final Form23 form23) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    final StringBuilder sql = new StringBuilder();
    sql.append("INSERT INTO `form23`").append(
            " (`form23_id`,`industry_id`,`factory_id`,`create_date`,`create_by`,`update_date`,`update_by`,"
                    + "`totalScrap`,`part4flag`,`part4fullName`,`part4Date`,"
                    + "`part5flag`,`part5licenseNo`,`part5licenseDate`,`part5billingNo`,`part5billingDate`,`part5amount`,`part5Date`,"
                    + "`part6flag`,`part6Date`,`step`)")
            .append(" VALUES ( NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'0')");

    logger.info("SQL : " + sql.toString());

    String user = "";
    try {//from ww  w .  j  a  v a2 s .c om
        user = BuckWaUtils.getUserNameFromContext();
    } catch (BuckWaException e) {
        e.printStackTrace();
    }
    final String userName = user;

    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            Timestamp currentDate = new Timestamp(System.currentTimeMillis());
            Industry industry = form23.getIndustry();
            Factory factory = form23.getFactory();

            PreparedStatement ps = connection.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
            ps.setLong(1, industry.getIndustryId());
            if (factory.getFactoryId() != null) {
                ps.setLong(2, factory.getFactoryId());
            } else {
                ps.setNull(2, java.sql.Types.BIGINT);
            }
            ps.setTimestamp(3, currentDate);
            ps.setString(4, userName);
            ps.setTimestamp(5, currentDate);
            ps.setString(6, userName);
            ps.setBigDecimal(7, form23.getTotalScrap());

            ps.setString(8, form23.getPart4flag());
            ps.setString(9, form23.getPart4fullName());
            ps.setTimestamp(10, currentDate);
            ps.setString(11, form23.getPart5flag());
            ps.setString(12, form23.getPart5licenseNo());
            ps.setTimestamp(13, getDateFormString(form23.getPart5licenseDate()));//part5licenseDate
            ps.setString(14, form23.getPart5billingNo());
            ps.setTimestamp(15, getDateFormString(form23.getPart5billingDate()));//part5billingDate
            ps.setBigDecimal(16, form23.getPart5amount());
            ps.setTimestamp(17, currentDate);//part5Date
            ps.setString(18, form23.getPart6flag());//part5Date
            ps.setTimestamp(19, currentDate);//part6Date

            return ps;
        }

    }, keyHolder);

    final Long returnidform23 = keyHolder.getKey().longValue();
    form23.setForm23Id(returnidform23);
    form23.setStep("0");
    logger.info("returnidform23 : " + returnidform23);

    //ID PRODUCT
    List<Product> products = form23.getProductList();
    if (products != null) {
        final StringBuilder psql = new StringBuilder();
        psql.append(
                "INSERT INTO `form23_product`(`form23_id`,`seq`,`productName`,`size`,`bandColor`,`backgroudColor`,`licenseNo`,`grossnumber200`,`grossnumber400`,`corkScrap`,`totalScrap`,`create_date`,`create_by`, `update_date`,`update_by`,`product_id`) ")
                .append("VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NULL)");

        logger.info("SQL : " + psql.toString());

        for (final Product p : products) {

            jdbcTemplate.update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    Timestamp currentDate = new Timestamp(System.currentTimeMillis());
                    PreparedStatement ps = connection.prepareStatement(psql.toString(),
                            Statement.RETURN_GENERATED_KEYS);
                    ps.setLong(1, returnidform23);
                    ps.setString(2, p.getSeq());
                    ps.setString(3, p.getProductName());
                    ps.setString(4, p.getSize());
                    ps.setString(5, p.getBandColor());
                    ps.setString(6, p.getBackgroudColor());
                    ps.setString(7, p.getLicenseNo());
                    ps.setBigDecimal(8, p.getGrossnumber200());
                    ps.setBigDecimal(9, p.getGrossnumber400());
                    ps.setBigDecimal(10, p.getCorkScrap());
                    ps.setBigDecimal(11, p.getTotalScrap());

                    ps.setTimestamp(12, currentDate);
                    ps.setString(13, userName);
                    ps.setTimestamp(14, currentDate);
                    ps.setString(15, userName);
                    return ps;
                }

            }, keyHolder);

            long returnidproduct = keyHolder.getKey().longValue();
            p.setProcuctId(returnidproduct);
            logger.info("returnidproduct : " + returnidproduct);
        }
    }
}

From source file:edu.jhu.pha.vospace.meta.MySQLMetaStore2.java

@Override
public void storeInfo(final VospaceId identifier, final NodeInfo info) {
    DbPoolServlet.goSql("Adding nodeinfo",
            "update nodes set size = ?, mimetype = ?, rev = ? where current_rev = 1 and node_id = "
                    + "(SELECT * FROM (SELECT nodes.node_id FROM nodes JOIN containers "
                    + "ON nodes.container_id = containers.container_id JOIN user_identities "
                    + "ON containers.user_id = user_identities.user_id WHERE `container_name` = ? AND `path` = ? AND `identity` = ?) a)",
            new SqlWorker<Integer>() {
                @Override/*from w ww.j  av  a2  s  .  c om*/
                public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                    stmt.setLong(1, info.getSize());
                    stmt.setString(2, info.getContentType());
                    stmt.setInt(3, info.getRevision());
                    stmt.setString(4, identifier.getNodePath().getContainerName());
                    stmt.setString(5, identifier.getNodePath().getNodeRelativeStoragePath());
                    stmt.setString(6, owner);
                    return stmt.executeUpdate();
                }
            });

}