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:com.surfs.storage.common.datasource.jdbc.JdbcDao.java

@Override
public int update(String poolName, String sql, Object... params) throws Exception {
    Connection conn = null;/*w  ww .j  a v  a2 s  .  c  om*/
    PreparedStatement ps = null;
    try {
        conn = getConnection(poolName);
        ps = conn.prepareStatement(sql);
        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]);
        }
        return ps.executeUpdate();
    } catch (Exception e) {
        throw e;
    } finally {
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnect(conn);
    }
}

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

@Override
public int delete(String poolName, String sql, Object... params) throws Exception {
    Connection conn = null;//from w w w. j  a  va2s. c om
    PreparedStatement ps = null;
    try {
        conn = getConnection(poolName);
        ps = conn.prepareStatement(sql);
        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]);
        }
        return ps.executeUpdate();
    } catch (Exception e) {
        throw e;
    } finally {
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnect(conn);
    }
}

From source file:com.l2jfree.gameserver.util.OfflineTradeManager.java

public void store() {
    _log.info("OfflineTradeManager: Storring...");
    _playerCount = 0;//from   w  w  w. ja v a2 s. c o  m
    _itemCount = 0;
    _recipeCount = 0;

    cleanTables();
    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        for (L2Player p : L2World.getInstance().getAllPlayers()) {
            try {
                if (p.isInOfflineMode()) {
                    final int privateStoreType = p.getPrivateStoreType();
                    TradeList tradeList = null;
                    L2ManufactureList manufactureList = null;

                    switch (privateStoreType) {
                    case L2Player.STORE_PRIVATE_SELL:
                    case L2Player.STORE_PRIVATE_PACKAGE_SELL:
                        tradeList = p.getSellList();
                        for (TradeItem i : tradeList.getItems()) {
                            PreparedStatement st2 = con
                                    .prepareStatement("INSERT INTO offline_traders_items VALUES(?,?,?,?)");
                            st2.setInt(1, p.getObjectId());
                            st2.setInt(2, i.getObjectId());
                            st2.setLong(3, i.getCount());
                            st2.setLong(4, i.getPrice());
                            st2.execute();
                            st2.close();

                            _itemCount++;
                        }
                        break;
                    case L2Player.STORE_PRIVATE_BUY:
                        tradeList = p.getBuyList();
                        for (TradeItem i : tradeList.getItems()) {
                            PreparedStatement st2 = con
                                    .prepareStatement("INSERT INTO offline_traders_items VALUES(?,?,?,?)");
                            st2.setInt(1, p.getObjectId());
                            st2.setInt(2, i.getItem().getItemId());
                            st2.setLong(3, i.getCount());
                            st2.setLong(4, i.getPrice());
                            st2.execute();
                            st2.close();

                            _itemCount++;
                        }
                        break;
                    case L2Player.STORE_PRIVATE_MANUFACTURE:
                        manufactureList = p.getCreateList();
                        for (L2ManufactureItem i : manufactureList.getList()) {
                            PreparedStatement st2 = con
                                    .prepareStatement("INSERT INTO offline_traders_items VALUES(?,?,?,?)");
                            st2.setInt(1, p.getObjectId());
                            st2.setInt(2, i.getRecipeId());
                            st2.setLong(3, -1);
                            st2.setLong(4, i.getCost());
                            st2.execute();
                            st2.close();

                            _recipeCount++;
                        }
                        break;
                    }
                    PreparedStatement st = con.prepareStatement("INSERT INTO offline_traders VALUES(?,?,?)");
                    st.setInt(1, p.getObjectId());
                    st.setString(2, String.valueOf(privateStoreType));
                    switch (privateStoreType) {
                    case L2Player.STORE_PRIVATE_MANUFACTURE:
                        if (manufactureList != null)
                            st.setString(3, manufactureList.getStoreName());
                        else
                            st.setString(3, "");
                        break;
                    case L2Player.STORE_PRIVATE_SELL:
                    case L2Player.STORE_PRIVATE_PACKAGE_SELL:
                    case L2Player.STORE_PRIVATE_BUY:
                        if (tradeList != null)
                            st.setString(3, tradeList.getTitle());
                        else
                            st.setString(3, "");
                        break;
                    default:
                        st.setString(3, "");
                    }

                    st.execute();
                    st.close();

                    _playerCount++;
                }
                //new Disconnection(p).defaultSequence(true);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    } catch (Exception e) {
        _log.error("OfflineTradeManager: Could not store char private store list: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
    _log.info("OfflineTradeManager: Stored " + _playerCount + " offline traders with " + _itemCount
            + " items and " + _recipeCount + " recipes!");
}

From source file:com.l2jfree.gameserver.model.entity.Auction.java

/** Save Auction Data End */
private void saveAuctionDate() {
    Connection con = null;// w ww .java  2s  . c o  m
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement("UPDATE auction SET endDate = ? WHERE id = ?");
        statement.setLong(1, _endDate);
        statement.setInt(2, _id);
        statement.execute();

        statement.close();
    } catch (Exception e) {
        _log.fatal("Exception: saveAuctionDate(): " + e.getMessage(), e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGMutatiesDAO.java

@Override
public void insert(final BAGMutatie mutatie) throws DAOException {
    try {/*from   ww w.ja  v a 2 s. c  o  m*/
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                try {
                    PreparedStatement ps = connection.prepareStatement("insert into bag_mutatie (" + "id,"
                            + "tijdstip_verwerking," + "volgnr_verwerking," + "object_type," + "mutatie_product"
                            + ") values ((select nvl(max(id),0) + 1 from bag_mutatie),?,?,?,?)");
                    ps.setTimestamp(1, Utils.toTimestamp(mutatie.getTijdstipVerwerking()));
                    ps.setLong(2, mutatie.getVolgnrVerwerking());
                    ps.setInt(3, mutatie.getObjectType().ordinal());
                    ps.setString(4, XMLMessageBuilder.getInstance(MutatieProduct.class)
                            .handle(new JAXBElement<MutatieProduct>(new QName(
                                    "http://www.kadaster.nl/schemas/bag-verstrekkingen/extract-producten-lvc/v20090901",
                                    "Mutatie-product"), MutatieProduct.class, mutatie.getMutatieProduct())));
                    return ps;
                } catch (JAXBException e) {
                    throw new DAOException(e);
                }
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}

From source file:fr.gael.dhus.database.liquibase.CopyProductImagesBlobToFile.java

/**
 * This method executes://from   www.  j  a v  a 2 s  .c  om
 *  - extraction of quicklooks and thumbnails from the database to files,
 *  - references these files into the data base.
 *  
 *  remove/update processes are let to liquibase scripts.
 */
@Override
public void execute(Database database) throws CustomChangeException {
    PreparedStatement products = null;
    ResultSet products_res = null;
    JdbcConnection db_connection = (JdbcConnection) database.getConnection();
    try {
        products = db_connection.prepareStatement("SELECT PRODUCT.ID ID,"
                + "       PRODUCT.DOWNLOAD_PATH DWN_PATH, " + "       PRODUCT.PATH PRODUCT_PATH,"
                + "       IMAGE.QUICKLOOK QUICKLOOK," + "       IMAGE.THUMBNAIL THUMBNAIL "
                + "FROM PRODUCTS PRODUCT, PRODUCT_IMAGES IMAGE " + "WHERE PRODUCT.IMAGES_ID=IMAGE.ID");
        products_res = products.executeQuery();
        while (products_res.next()) {
            Blob ql = (Blob) products_res.getObject("QUICKLOOK");
            Blob th = (Blob) products_res.getObject("THUMBNAIL");
            long id = products_res.getLong("ID");
            String download_path = products_res.getString("DWN_PATH");
            String product_path = products_res.getString("PRODUCT_PATH");

            if (download_path == null) {
                logger.error("No download path for product '" + product_path + "': product images not managed");
                continue;
            }

            // copy blobs into files and update products table
            if (ql != null) {
                // Copy file
                String ql_path = download_path.replaceAll("(?i)(.*).zip", "$1-ql.gif");
                blobToFile(ql, ql_path);

                // Update products table
                PreparedStatement product_flags_stmt = null;
                // Add related flags
                try {
                    product_flags_stmt = db_connection
                            .prepareStatement("UPDATE PRODUCTS SET QUICKLOOK_PATH=? WHERE ID=?");
                    product_flags_stmt.setString(1, ql_path);
                    product_flags_stmt.setLong(2, id);
                    product_flags_stmt.execute();
                } finally {
                    if (product_flags_stmt != null)
                        try {
                            product_flags_stmt.close();
                        } catch (Exception e) {
                            logger.warn("Cannot close Statement !");
                        }
                }
            }

            if (th != null) {
                String th_path = download_path.replaceAll("(?i)(.*).zip", "$1-th.gif");
                blobToFile(th, th_path);
                // Update products table
                PreparedStatement product_flags_stmt = null;
                // Add related flags
                try {
                    product_flags_stmt = db_connection
                            .prepareStatement("UPDATE PRODUCTS SET THUMBNAIL_PATH=? WHERE ID=?");
                    product_flags_stmt.setString(1, th_path);
                    product_flags_stmt.setLong(2, id);
                    product_flags_stmt.execute();
                } finally {
                    if (product_flags_stmt != null)
                        try {
                            product_flags_stmt.close();
                        } catch (Exception e) {
                            logger.warn("Cannot close Statement !");
                        }
                }
            }
        }
        // RUN CHECKPOINT TO clean lob data
        PreparedStatement product_flags_stmt = null;
        try {
            product_flags_stmt = db_connection.prepareStatement("CHECKPOINT DEFRAG");
            product_flags_stmt.execute();
        } catch (Exception e) {
            logger.error("Cannot perform database checkpoint defrag command", e);
        } finally {
            if (product_flags_stmt != null)
                try {
                    product_flags_stmt.close();
                } catch (Exception e) {
                    logger.warn("Cannot close Statement !", e);
                }
        }
    } catch (Exception e) {
        throw new CustomChangeException("Cannot move Blobs from product", e);
    } finally {
        if (products_res != null) {
            try {
                products_res.close();
            } catch (Exception e) {
                logger.warn("Cannot close ResultSet !");
            }
        }
        if (products != null) {
            try {
                products.close();
            } catch (Exception e) {
                logger.warn("Cannot close Statement !");
            }
        }
        //if (db_connection!=null) try { db_connection.close (); }
        // catch (Exception e) {}
    }
}

From source file:architecture.user.dao.impl.ExternalJdbcUserDao.java

public void switchCompanies(long companyId, Set<Long> users) {

    final List<Long> userIdsToUse = Lists.newArrayListWithExpectedSize(users.size());
    for (Long userId : users) {
        userIdsToUse.add(userId);// ww  w . j  av a  2  s.com
    }

    final Long companyIdToUse = companyId;
    getExtendedJdbcTemplate().batchUpdate(getSql("UPDATE_USER_COMPANY"), new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setLong(1, companyIdToUse);
            ps.setLong(2, userIdsToUse.get(i));
        }

        public int getBatchSize() {
            return userIdsToUse.size();
        }
    });
}

From source file:com.glaf.core.execution.FileExecutionHelper.java

public void save(Connection connection, String serviceKey, File file) {
    String sql = " insert into " + BlobItemDomainFactory.TABLENAME
            + " (ID_, BUSINESSKEY_, FILEID_, SERVICEKEY_, NAME_, TYPE_, FILENAME_, PATH_, LASTMODIFIED_, LOCKED_, STATUS_, DATA_, CREATEBY_, CREATEDATE_)"
            + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
    PreparedStatement psmt = null;
    try {//  w ww.  j  a v a2  s  .c  om
        psmt = connection.prepareStatement(sql);
        psmt.setString(1, UUID32.getUUID());
        psmt.setString(2, serviceKey);
        psmt.setString(3, DigestUtils.md5Hex(file.getAbsolutePath()));
        psmt.setString(4, serviceKey);
        psmt.setString(5, file.getName());
        psmt.setString(6, "Execution");
        psmt.setString(7, file.getAbsolutePath());
        psmt.setString(8, file.getAbsolutePath());
        psmt.setLong(9, file.lastModified());
        psmt.setInt(10, 0);
        psmt.setInt(11, 1);
        psmt.setBytes(12, FileUtils.getBytes(file));
        psmt.setString(13, "system");
        psmt.setTimestamp(14, DateUtils.toTimestamp(new java.util.Date()));
        psmt.executeUpdate();
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
    }
}

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

@Override
public void save(User user) {
    String sql;//  w  w  w .  j  av  a 2  s .  co m
    if (user.getKey() == null) {
        sql = "insert into user (loginid, roles, updated, created, password) values (?,?,?,?,?)";
    } else {
        sql = "update user set loginid = ?," + "roles = ?," + "updated = ? where id = ? limit 1";
    }
    Connection conn = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, user.getLoginId());
        st.setString(2, Functions.join(user.getRoles(), ","));
        st.setTimestamp(3, new Timestamp(new Date().getTime()));
        if (user.getKey() != null) {
            st.setLong(4, user.getKey());
        } else {
            st.setTimestamp(4, new Timestamp(new Date().getTime()));
            st.setString(5, user.getPassword());
        }
        st.executeUpdate();
        if (user.getKey() == null) {
            ResultSet rs = st.getGeneratedKeys();
            if (rs != null && rs.next()) {
                user.setKey(rs.getLong(1));
            } else {
                logger.warn("Couldn't get id for user {}", user.getLoginId());
            }
        }
    } catch (SQLException e) {
        logger.error("Save: {}", e);
    } catch (IOException e) {
        logger.error("Save: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:cz.muni.fi.javaseminar.kafa.bookregister.BookManagerImpl.java

@Override
@Transactional(readOnly = false)//from   w w  w. j  av a2  s . c  om
public void createBook(Book book) {
    validate(book);
    if (book.getId() != null) {
        throw new IllegalArgumentException("book id is already set");
    }

    KeyHolder keyHolder = new GeneratedKeyHolder();
    int updated = jdbcTemplate.update((Connection connection) -> {
        PreparedStatement ps = connection.prepareStatement(
                "INSERT INTO BOOK (name,isbn,published,author_id) VALUES (?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, book.getName());
        ps.setString(2, book.getIsbn());
        Date date = Date.valueOf(book.getPublished());
        ps.setDate(3, date);
        if (book.getAuthorId() == null) {
            ps.setNull(4, Types.BIGINT);
        } else {
            ps.setLong(4, book.getAuthorId());
        }
        return ps;
    }, keyHolder);

    book.setId(keyHolder.getKey().longValue());

    DBUtils.checkUpdatesCount(updated, book, true);
}