Example usage for java.sql PreparedStatement execute

List of usage examples for java.sql PreparedStatement execute

Introduction

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

Prototype

boolean execute() throws SQLException;

Source Link

Document

Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.

Usage

From source file:com.qcloud.component.snaker.access.mybatis.MybatisAccess.java

/**
 * JDBC?BLOB/*from  www.j  a v a 2s .  co  m*/
 */
public void updateProcess(Process process) {

    super.updateProcess(process);
    SqlSession sqlSession = getSession();
    if (process.getBytes() != null) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = sqlSession.getConnection();
            pstmt = conn.prepareStatement(PROCESS_UPDATE_BLOB);
            pstmt.setBytes(1, process.getBytes());
            pstmt.setString(2, process.getId());
            pstmt.execute();
        } catch (Exception e) {
            throw new SnakerException(e.getMessage(), e.getCause());
        } finally {
            try {
                JdbcHelper.close(pstmt);
                SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
            } catch (SQLException e) {
                throw new SnakerException(e.getMessage(), e.getCause());
            }
        }
    }
}

From source file:com.l2jfree.gameserver.instancemanager.CoupleManager.java

public void deleteCouple(int coupleId) {
    int index = getCoupleIndex(coupleId);
    Couple couple = getCouples().get(index);
    if (couple != null) {
        L2Player player1 = L2World.getInstance().getPlayer(couple.getPlayer1Id());
        L2Player player2 = L2World.getInstance().getPlayer(couple.getPlayer2Id());
        L2ItemInstance item = null;/*from  ww w  .  j a v a 2  s .  c  o  m*/
        if (player1 != null) {
            player1.setPartnerId(0);
            player1.setMaried(false);
            player1.setCoupleId(0);
            item = player1.getInventory().getItemByItemId(9140);
            if (player1.isOnline() == 1 && item != null) {
                player1.destroyItem("Removing Cupids Bow", item, player1, true);

                // No need to update every item in the inventory
                //player1.getInventory().updateDatabase();
            }
            if (player1.isOnline() == 0 && item != null) {
                Integer PlayerId = player1.getObjectId();
                Integer ItemId = 9140;
                Connection con = null;
                try {
                    con = L2DatabaseFactory.getInstance().getConnection(con);
                    PreparedStatement statement = con
                            .prepareStatement("DELETE FROM items WHERE owner_id = ? AND item_id = ?");
                    statement.setInt(1, PlayerId);
                    statement.setInt(2, ItemId);
                    statement.execute();
                    statement.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    L2DatabaseFactory.close(con);
                }
            }
        }
        if (player2 != null) {
            player2.setPartnerId(0);
            player2.setMaried(false);
            player2.setCoupleId(0);
            item = player2.getInventory().getItemByItemId(9140);
            if (player2.isOnline() == 1 && item != null) {
                player2.destroyItem("Removing Cupids Bow", item, player2, true);

                // No need to update every item in the inventory
                //player2.getInventory().updateDatabase();
            }
            if (player2.isOnline() == 0 && item != null) {
                Integer Player2Id = player2.getObjectId();
                Integer Item2Id = 9140;
                Connection con = null;
                try {
                    con = L2DatabaseFactory.getInstance().getConnection(con);
                    PreparedStatement statement = con
                            .prepareStatement("DELETE FROM items WHERE owner_id = ? AND item_id = ?");
                    statement.setInt(1, Player2Id);
                    statement.setInt(2, Item2Id);
                    statement.execute();
                    statement.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    L2DatabaseFactory.close(con);
                }
            }
        }
        couple.divorce();
        getCouples().remove(index);
    }
}

From source file:mx.com.pixup.portal.dao.FormaPagoDaoJdbc.java

@Override
public void deleteFormaPago(FormaPago formaPago) {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;//from  w  w w .ja va2 s .c  o m

    String sql = "delete from forma_pago where id = ?";

    try {
        connection = dataSource.getConnection();

        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, formaPago.getId());

        preparedStatement.execute();

    } catch (Exception e) {

    } finally {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }

    }

}

From source file:de.iritgo.aktario.jdbc.JDBCIDGenerator.java

/**
 * Allocate new ids./* w  w w.j  a  va 2s.com*/
 */
protected void allocateIds() {
    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;
    PreparedStatement stmt = null;

    try {
        connection = dataSource.getConnection();

        stmt = connection.prepareStatement("update IritgoProperties set value=? where name=?");
        stmt.setLong(1, id + chunk * step);
        stmt.setString(2, "persist.ids.nextvalue");
        stmt.execute();

        free = chunk;

        Log.logVerbose("persist", "JDBCIDGenerator", "Successfully allocated new ids (id=" + id + ")");
    } catch (Exception x) {
        Log.logFatal("persist", "JDBCIDGenerator", "Error while allocating new ids: " + x);
    } finally {
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.l2jfree.gameserver.communitybbs.bb.Post.java

/**
 * @param i/*  ww w.j a va 2s .  c om*/
 */
public void updatetxt(int i) {
    Connection con = null;
    try {
        CPost cp = getCPost(i);
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(
                "UPDATE posts SET post_txt=? WHERE post_id=? AND post_topic_id=? AND post_forum_id=?");
        statement.setString(1, cp.postTxt);
        statement.setInt(2, cp.postId);
        statement.setInt(3, cp.postTopicId);
        statement.setInt(4, cp.postForumId);
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("error while saving new Post to db ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.cloudera.sqoop.tool.EvalSqlTool.java

@Override
/** {@inheritDoc} */
public int run(SqoopOptions options) {
    if (!init(options)) {
        return 1;
    }//from  w w  w.  j  a  v a  2s.c  o  m

    PreparedStatement stmt = null;
    ResultSet rs = null;
    PrintWriter pw = null;
    try {
        Connection c = manager.getConnection();
        String query = options.getSqlQuery();
        LOG.debug("SQL query: " + query);
        stmt = c.prepareStatement(query);
        boolean resultType = stmt.execute();
        // Iterate over all the results from this statement.
        while (true) {
            LOG.debug("resultType=" + resultType);
            if (!resultType) {
                // This result was an update count.
                int updateCount = stmt.getUpdateCount();
                LOG.debug("updateCount=" + updateCount);
                if (updateCount == -1) {
                    // We are done iterating over results from this statement.
                    c.commit();
                    break;
                } else {
                    LOG.info(updateCount + " row(s) updated.");
                }
            } else {
                // This yields a ResultSet.
                rs = stmt.getResultSet();
                pw = new PrintWriter(System.out, true);
                new ResultSetPrinter().printResultSet(pw, rs);
                pw.close();
                pw = null;
            }

            resultType = stmt.getMoreResults();
        }
    } catch (IOException ioe) {
        LOG.warn("IOException formatting results: " + StringUtils.stringifyException(ioe));
        return 1;
    } catch (SQLException sqlE) {
        LOG.warn("SQL exception executing statement: " + StringUtils.stringifyException(sqlE));
        return 1;
    } finally {
        if (null != pw) {
            pw.close();
        }
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException sqlE) {
                LOG.warn("SQL exception closing ResultSet: " + StringUtils.stringifyException(sqlE));
            }
        }
        if (null != stmt) {
            try {
                stmt.close();
            } catch (SQLException sqlE) {
                LOG.warn("SQL exception closing statement: " + StringUtils.stringifyException(sqlE));
            }
        }
        destroy(options);
    }

    return 0;
}

From source file:com.flexive.core.Database.java

/**
 * Store a FxString in a translation table that only consists of n translation columns
 *
 * @param string     string to be stored
 * @param con        existing connection
 * @param table      storage table/* ww w. ja  va 2s.  c o  m*/
 * @param dataColumn names of the data columns
 * @param idColumn   name of the id column
 * @param id         id of the given string
 * @throws SQLException if a database error occured
 */
public static void storeFxString(FxString[] string, Connection con, String table, String[] dataColumn,
        String idColumn, long id) throws SQLException {
    PreparedStatement ps = null;
    if (string.length != dataColumn.length)
        throw new SQLException("string.length != dataColumn.length");
    for (FxString param : string) {
        if (!param.isMultiLanguage()) {
            throw new FxInvalidParameterException("string", LOG, "ex.db.fxString.store.multilang", table)
                    .asRuntimeException();
        }
    }
    try {
        ps = con.prepareStatement("DELETE FROM " + table + ML + " WHERE " + idColumn + "=?");
        ps.setLong(1, id);
        ps.execute();

        //find languages to write
        List<Long> langs = new ArrayList<Long>(5);
        for (FxString curr : string)
            for (long currLang : curr.getTranslatedLanguages())
                if (curr.translationExists(currLang)) {
                    if (!langs.contains(currLang))
                        langs.add(currLang);
                }
        if (langs.size() > 0) {
            StringBuffer sql = new StringBuffer(300);
            sql.append("INSERT INTO ").append(table).append(ML + "(").append(idColumn).append(",LANG");
            for (String dc : dataColumn)
                sql.append(',').append(dc).append(',').append(dc).append("_MLD");
            sql.append(")VALUES(?,?");
            //noinspection UnusedDeclaration
            for (FxString aString : string)
                sql.append(",?,?");
            sql.append(')');
            ps.close();
            ps = con.prepareStatement(sql.toString());
            boolean hasData;
            for (long lang : langs) {
                hasData = false;
                ps.setLong(1, id);
                ps.setInt(2, (int) lang);
                for (int i = 0; i < string.length; i++) {
                    if (FxString.EMPTY.equals(string[i].getTranslation(lang))) {
                        ps.setNull(3 + i * 2, java.sql.Types.VARCHAR);
                        ps.setBoolean(3 + 1 + i * 2, false);
                    } else {
                        ps.setString(3 + i * 2, string[i].getTranslation(lang)); //get translation or empty string
                        ps.setBoolean(3 + 1 + i * 2, string[i].isDefaultLanguage(lang));
                        hasData = true;
                    }
                }
                if (hasData)
                    ps.executeUpdate();
            }
        }
    } finally {
        if (ps != null)
            ps.close();
    }
}

From source file:at.becast.youploader.account.Account.java

public int save() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    LOG.info("Saving account");
    try {//  w  w w  .  j  av  a  2  s .  c  o  m
        PreparedStatement stmt = c
                .prepareStatement("INSERT INTO `accounts` (`name`,`refresh_token`,`cookie`) VALUES(?,?,?)");
        stmt.setString(1, this.name);
        stmt.setString(2, this.refreshToken);
        stmt.setString(3, mapper.writeValueAsString(this.cdata));
        stmt.execute();
        ResultSet rs = stmt.getGeneratedKeys();
        stmt.close();
        if (rs.next()) {
            int id = rs.getInt(1);
            rs.close();
            LOG.info("Account saved");
            return id;
        } else {
            LOG.error("Could not save account {}!", this.name);
            return -1;
        }
    } catch (SQLException e) {
        LOG.error("Could not save account Ex:", e);
        return -1;
    }
}

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

public synchronized void deleteShortCut(int slot, int page) {
    L2ShortCut old = _shortCuts.remove(slot + page * 12);
    if (old == null)
        return;//ww w . ja v a  2s  . c o m

    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);

        PreparedStatement statement = con.prepareStatement(
                "DELETE FROM character_shortcuts WHERE charId=? AND slot=? AND page=? AND class_index=?");
        statement.setInt(1, _owner.getObjectId());
        statement.setInt(2, old.getSlot());
        statement.setInt(3, old.getPage());
        statement.setInt(4, _owner.getClassIndex());
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    if (old.getType() == L2ShortCut.TYPE_ITEM) {
        L2ItemInstance item = _owner.getInventory().getItemByObjectId(old.getId());

        if (item != null && item.getItemType() == L2EtcItemType.SHOT)
            _owner.getShots().removeAutoSoulShot(item.getItemId());
    }

    _owner.sendPacket(new ShortCutInit(_owner));

    for (int shotId : _owner.getShots().getAutoSoulShots())
        _owner.sendPacket(new ExAutoSoulShot(shotId, 1));
}

From source file:com.demandware.vulnapp.challenge.impl.SQLIChallenge.java

/**
 * execute the vulnerable challenge query
 * @param holder dbholder to use for query
 * @param query query to run (user input)
 * @return executed statement/*from w w  w .  j  a  v  a 2  s  .c  om*/
 * @throws SQLException if sql error occurs
 */
private PreparedStatement makeChallengeQuery(DBHolder holder, String query) throws SQLException {
    String sql = generateSQLChallengeStatement(query);
    Connection conn = holder.getConnection();
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.execute();
    return stmt;
}