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.l2jfree.gameserver.instancemanager.CastleManager.java

public void removeCirclet(L2ClanMember member, int castleId) {
    if (member == null)
        return;//from  w  ww . ja  v  a  2s .c  om
    L2Player player = member.getPlayerInstance();
    int circletId = getCircletByCastleId(castleId);

    if (circletId != 0) {
        // Online Player circlet removal
        if (player != null && player.getInventory() != null) {
            L2ItemInstance circlet = player.getInventory().getItemByItemId(circletId);
            if (circlet != null) {
                if (circlet.isEquipped())
                    player.getInventory().unEquipItemInSlotAndRecord(circlet.getLocationSlot());
                player.destroyItemByItemId("CastleCircletRemoval", circletId, 1, player, true);
            }
            return;
        }
        // Else Offline Player circlet removal
        Connection con = null;
        try {
            con = L2DatabaseFactory.getInstance().getConnection();
            PreparedStatement statement = con
                    .prepareStatement("DELETE FROM items WHERE owner_id = ? and item_id = ?");
            statement.setInt(1, member.getObjectId());
            statement.setInt(2, circletId);
            statement.execute();
            statement.close();
        } catch (SQLException e) {
            _log.error("Failed to remove castle circlets offline for player " + member.getName(), e);
        } finally {
            L2DatabaseFactory.close(con);
        }
    }
}

From source file:ccc.migration.DbUtilsDB.java

/** {@inheritDoc} */
@Override/*from   w ww  .j  a  v  a 2 s .c om*/
@SuppressWarnings("unchecked")
public <T> T select(final SqlQuery<T> q, final Object... param) {

    try {
        log.debug("Query: " + q.getSql());
        log.debug("Params: " + Arrays.asList(param));

        final PreparedStatement s = _c.prepareStatement(q.getSql());
        try {
            int index = 1;
            for (final Object o : param) {
                s.setObject(index, o);
                index++;
            }

            log.debug("Running query.");
            final boolean resultsReturned = s.execute();
            log.debug("Running finished.");

            if (!resultsReturned) {
                throw new MigrationException("Query returned no results.");
            }

            final ResultSet rs = s.getResultSet();

            try {
                final Object result = q.handle(rs);
                return (T) result;

            } catch (final SQLException e) {
                throw new MigrationException(e);
            } finally {
                DbUtils.closeQuietly(rs);
            }

        } catch (final SQLException e) {
            throw new MigrationException(e);
        } finally {
            DbUtils.closeQuietly(s);
        }

    } catch (final SQLException e) {
        throw new MigrationException(e);
    }
}

From source file:dao.MaterialDaoImplem.java

@Override
public int insertMaterial(Material material) {
    try (Connection connection = dataSource.getConnection()) {
        String query = ("INSERT INTO Material (name, weight, manufacturer,cost,quantity) values(?,?,?,?,?)");
        PreparedStatement stat = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        stat.setString(1, material.getName());
        stat.setInt(2, material.getWeight());
        stat.setString(3, material.getManufacturer());
        stat.setInt(4, material.getCost());
        stat.setInt(5, material.getQuantity());
        stat.execute();
        ResultSet res = stat.getGeneratedKeys();
        if (res.next()) {
            return res.getInt(1);
        } else {//from   w w w .ja va2s. com
            throw new RuntimeException("? ?    ");
        }
    } catch (Exception e) {
        throw new RuntimeException("Error:insertMaterial", e);
    }
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testInsertFromJoinWithImplicitCast() throws Exception {
    Connection conn = methodWatcher.getOrCreateConnection();
    String sql = "insert into TABLE_RESULT select A.CUSTOMER_ID from TABLE_BIGINT A "
            + "where NOT EXISTS (SELECT * from TABLE_DECIMAL B where A.CUSTOMER_ID = B.CUSTOMER_ID)";
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.execute();

    ps = conn.prepareStatement("select * from TABLE_RESULT order by 1");
    ResultSet rs = ps.executeQuery();
    int i = 1;/*from w  w  w .  ja va  2  s.  c o  m*/
    while (rs.next()) {
        Assert.assertEquals("Wrong result", i++, rs.getInt(1));
    }
    rs.close();

    ps = conn.prepareStatement("truncate table TABLE_RESULT");
    ps.execute();

    sql = "insert into TABLE_RESULT select A.CUSTOMER_ID from TABLE_BIGINT A "
            + "where NOT EXISTS (SELECT * from TABLE_DECIMAL B where B.CUSTOMER_ID = A.CUSTOMER_ID)";
    ps = conn.prepareStatement(sql);
    ps.execute();

    ps = conn.prepareStatement("select * from TABLE_RESULT order by 1");
    rs = ps.executeQuery();
    i = 1;
    while (rs.next()) {
        Assert.assertEquals("Wrong result", i++, rs.getInt(1));
    }
    rs.close();
}

From source file:edu.umd.cs.psl.database.rdbms.RDBMSDataStoreMetadata.java

/**** Database Helper functions ****/
protected boolean addRow(String mdTableName, String space, String type, String key, String val) {
    try {/*from w w  w  . j a v  a  2 s . co m*/
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + mdTableName + " VALUES(?, ?, ?, ?)");
        stmt.setString(1, space);
        stmt.setString(2, type);
        stmt.setString(3, key);
        stmt.setString(4, val);
        stmt.execute();
    } catch (Exception e) {
        log.info("Error adding row to metadata - " + e.getMessage());
        return false;
    }
    return true;
}

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

public void marry() {
    Connection con = null;// ww w.ja v a 2s. com
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement;

        statement = con.prepareStatement("UPDATE couples set maried = ?, weddingDate = ? where id = ?");
        statement.setBoolean(1, true);
        _weddingDate = System.currentTimeMillis();
        statement.setLong(2, _weddingDate);
        statement.setInt(3, _id);
        statement.execute();
        statement.close();
        _maried = true;
    } catch (Exception e) {
        _log.error("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:edu.umd.cs.psl.database.rdbms.RDBMSDataStoreMetadata.java

protected boolean removeRow(String mdTableName, String space, String type, String key) {
    try {/*w  w  w .  j a v a  2s.c  o m*/
        PreparedStatement stmt = conn.prepareStatement(
                "DELETE FROM " + mdTableName + " WHERE namespace = ? AND keytype = ? AND key = ?");
        stmt.setString(1, space);
        stmt.setString(2, type);
        stmt.setString(3, key);
        stmt.execute();
    } catch (Exception e) {
        log.info("Error removing row - " + e.getMessage());
        return false;
    }
    return true;
}

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

private void deleteItemsInDb() {
    Connection con = null;//from w  w w  .  j a va  2  s .  co m

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(DELETE_ITEMS);
        statement.execute();
        statement.close();
    } catch (SQLException e) {
        _log.error("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

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

private void deleteSkillsInDb() {
    Connection con = null;//  www .j  a va 2s .  c  o m

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(DELETE_SKILLS);
        statement.execute();
        statement.close();
    } catch (SQLException e) {
        _log.error(e.getMessage(), e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.github.brandtg.switchboard.TestMysqlLogServer.java

@Test
public void testMysqlEventListener() throws Exception {
    try (Connection conn = DriverManager.getConnection(jdbc, "root", "")) {
        // Write some rows, so we have binlog entries
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO simple VALUES(?, ?)");
        for (int i = 0; i < 10; i++) {
            pstmt.setInt(1, i);// w  ww . j a v a2s  . com
            pstmt.setInt(2, i);
            pstmt.execute();
        }
    }

    final AtomicInteger insertCount = new AtomicInteger();
    final AtomicInteger beginCount = new AtomicInteger();
    final AtomicInteger commitCount = new AtomicInteger();
    final AtomicInteger rollbackCount = new AtomicInteger();
    InetSocketAddress sourceAddress = new InetSocketAddress(8080);
    InetSocketAddress sinkAddress = new InetSocketAddress(9090);
    MysqlEventListener eventListener = new MysqlEventListener("test", sourceAddress, sinkAddress) {
        @Override
        public void onBegin(UUID sourceId, long transactionId) {
            beginCount.incrementAndGet();
        }

        @Override
        public void onInsert(List<Row> rows) {
            insertCount.incrementAndGet();
        }

        @Override
        public void onUpdate(List<Pair<Row>> rows) {

        }

        @Override
        public void onDelete(List<Row> rows) {

        }

        @Override
        public void onCommit() {
            commitCount.incrementAndGet();
        }

        @Override
        public void onRollback() {
            rollbackCount.incrementAndGet();
        }
    };

    try {
        eventListener.start();

        long startTime = System.currentTimeMillis();
        long currentTime = startTime;
        do {
            // Once we've seen all writes, check expected state
            if (insertCount.get() == 10) {
                Assert.assertEquals(beginCount.get(), 10);
                Assert.assertEquals(commitCount.get(), 10);
                Assert.assertEquals(rollbackCount.get(), 0);
                return;
            }
            Thread.sleep(pollMillis);
            currentTime = System.currentTimeMillis();
        } while (currentTime - startTime < timeoutMillis);
    } finally {
        eventListener.shutdown();
    }

    Assert.fail("Timed out while polling");
}