Example usage for java.sql PreparedStatement setInt

List of usage examples for java.sql PreparedStatement setInt

Introduction

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

Prototype

void setInt(int parameterIndex, int x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java int value.

Usage

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

public void load() {
    Connection con = null;/*from w ww .  j av  a2s. c  o m*/

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

        PreparedStatement statement = con
                .prepareStatement("SELECT * FROM grandboss_intervallist WHERE bossId = ?");
        statement.setInt(1, _bossId);
        ResultSet rset = statement.executeQuery();

        while (rset.next()) {
            _respawnDate = rset.getLong("respawnDate");

            if (_respawnDate - System.currentTimeMillis() <= 0) {
                _state = StateEnum.NOTSPAWN;
            } else {
                int tempState = rset.getInt("state");
                if (tempState == StateEnum.NOTSPAWN.ordinal())
                    _state = StateEnum.NOTSPAWN;
                else if (tempState == StateEnum.INTERVAL.ordinal())
                    _state = StateEnum.INTERVAL;
                else if (tempState == StateEnum.ALIVE.ordinal())
                    _state = StateEnum.ALIVE;
                else if (tempState == StateEnum.DEAD.ordinal())
                    _state = StateEnum.DEAD;
                else
                    _state = StateEnum.NOTSPAWN;
            }
        }
        rset.close();
        statement.close();
    } catch (Exception e) {
        _log.error(e.getMessage(), e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.taobao.tddl.jdbc.group.integration.CRUDTest.java

    () throws Exception {
   TGroupDataSource ds = new TGroupDataSource();
   DataSourceWrapper dsw = new DataSourceWrapper("db1", "rw", DataSourceFactory.getMySQLDataSource(), DBType.MYSQL);
   ds.init(dsw);//  w ww.  java  2  s.c om
      
   Connection conn = ds.getConnection();

   //Statementcrud
   Statement stmt = conn.createStatement();
   assertEquals(stmt.executeUpdate("insert into crud(f1,f2) values(10,'str')"), 1);
   assertEquals(stmt.executeUpdate("update crud set f2='str2'"), 1);
   ResultSet rs = stmt.executeQuery("select f1,f2 from crud");
   rs.next();
   assertEquals(rs.getInt(1), 10);
   assertEquals(rs.getString(2), "str2");
   assertEquals(stmt.executeUpdate("delete from crud"), 1);
   rs.close();
   stmt.close();

   //PreparedStatementcrud
   String sql = "insert into crud(f1,f2) values(?,?)";
   PreparedStatement ps = conn.prepareStatement(sql);
   ps.setInt(1, 10);
   ps.setString(2, "str");
   assertEquals(ps.executeUpdate(), 1);
   ps.close();

   sql = "update crud set f2=?";
   ps = conn.prepareStatement(sql);
   ps.setString(1, "str2");
   assertEquals(ps.executeUpdate(), 1);
   ps.close();

   sql = "select f1,f2 from crud";
   ps = conn.prepareStatement(sql);
   rs = ps.executeQuery();
   rs.next();
   assertEquals(rs.getInt(1), 10);
   assertEquals(rs.getString(2), "str2");
   rs.close();
   ps.close();

   sql = "delete from crud";
   ps = conn.prepareStatement(sql);
   assertEquals(ps.executeUpdate(), 1);
   ps.close();

   conn.close();
}

From source file:oobbit.orm.Links.java

public Link getOne(int id) throws SQLException, NothingWasFoundException {
    PreparedStatement statement = getConnection().prepareStatement(
            "SELECT * FROM oobbit.links AS q1 LEFT JOIN users AS q2 ON q1.creator = q2.user_id WHERE link_id = ?;");
    statement.setInt(1, id);

    ResultSet query = statement.executeQuery();

    if (query.next()) {
        Link link = new Link();
        link.parse(query);//from w w  w.  j av  a 2s  .  c om

        User user = new User();
        user.parse(query);
        link.setCreator(user);

        return link;
    } else {
        throw new NothingWasFoundException();
    }
}

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

public void save() {
    Connection con = null;//w  w w  . j a v a2 s.  c o  m

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(
                "INSERT INTO grandboss_intervallist (bossId,respawnDate,state) VALUES(?,?,?)");
        statement.setInt(1, _bossId);
        statement.setLong(2, _respawnDate);
        statement.setInt(3, _state.ordinal());
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.error(e.getMessage(), e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:fll.web.playoff.Playoff.java

/**
 * Find the playoff round run number for the specified division and
 * performance/*from   ww w.ja  va 2 s .  c om*/
 * run number in the current tournament.
 * 
 * @return the playoff round or -1 if not found
 */
public static int getPlayoffRound(final Connection connection, final String division, final int runNumber)
        throws SQLException {

    final int tournament = Queries.getCurrentTournament(connection);
    PreparedStatement prep = null;
    ResultSet rs = null;
    try {
        prep = connection.prepareStatement("SELECT PlayoffRound FROM PlayoffData" + " WHERE Tournament = ?"
                + " AND event_division = ?" + " AND run_number = ?");
        prep.setInt(1, tournament);
        prep.setString(2, division);
        prep.setInt(3, runNumber);
        rs = prep.executeQuery();
        if (rs.next()) {
            final int playoffRound = rs.getInt(1);
            return playoffRound;
        } else {
            return -1;
        }
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(prep);
    }
}

From source file:com.l2jfree.gameserver.model.entity.faction.FactionMember.java

public void quitFaction() {
    Connection con = null;//from w w w .  java 2  s  .  co  m
    _factionId = 0;
    _factionPoints = 0;
    _contributions = 0;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement;

        statement = con.prepareStatement("DELETE FROM faction_members WHERE player_id=?");
        statement.setInt(1, _playerId);
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("Exception: FactionMember.quitFaction(): " + e.getMessage(), e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.taobao.tddl.jdbc.group.integration.CRUDTest.java

    @Test
public void DataSourceWrapper() throws Exception {
   List<DataSourceWrapper> dataSourceWrappers = new ArrayList<DataSourceWrapper>();
   dataSourceWrappers.add(new DataSourceWrapper("dbKey1","rw", DataSourceFactory.getMySQLDataSource(1), DBType.MYSQL));
   dataSourceWrappers.add(new DataSourceWrapper("dbKey2","r", DataSourceFactory.getMySQLDataSource(2), DBType.MYSQL));

   TGroupDataSource ds = new TGroupDataSource();
   ds.setDbGroupKey("myDbGroupKey");
   ds.init(dataSourceWrappers);/*  www.  ja v a  2s.c  om*/

   Connection conn = ds.getConnection();

   //Statementcrud
   Statement stmt = conn.createStatement();
   assertEquals(stmt.executeUpdate("insert into crud(f1,f2) values(10,'str')"), 1);
   assertEquals(stmt.executeUpdate("update crud set f2='str2'"), 1);
   ResultSet rs = stmt.executeQuery("select f1,f2 from crud");
   rs.next();
   assertEquals(rs.getInt(1), 10);
   assertEquals(rs.getString(2), "str2");
   assertEquals(stmt.executeUpdate("delete from crud"), 1);
   rs.close();
   stmt.close();

   //PreparedStatementcrud
   String sql = "insert into crud(f1,f2) values(?,?)";
   PreparedStatement ps = conn.prepareStatement(sql);
   ps.setInt(1, 10);
   ps.setString(2, "str");
   assertEquals(ps.executeUpdate(), 1);
   ps.close();

   sql = "update crud set f2=?";
   ps = conn.prepareStatement(sql);
   ps.setString(1, "str2");
   assertEquals(ps.executeUpdate(), 1);
   ps.close();

   sql = "select f1,f2 from crud";
   ps = conn.prepareStatement(sql);
   rs = ps.executeQuery();
   rs.next();
   assertEquals(rs.getInt(1), 10);
   assertEquals(rs.getString(2), "str2");
   rs.close();
   ps.close();

   sql = "delete from crud";
   ps = conn.prepareStatement(sql);
   assertEquals(ps.executeUpdate(), 1);
   ps.close();

   conn.close();
}

From source file:com.nabla.dc.server.xml.settings.XmlUser.java

public boolean save(final Connection conn, final SaveContext ctx) throws SQLException, DispatchException {
    Integer userId = ctx.getUserIds().get(getName());
    if (userId != null) {
        if (ctx.getOption() == SqlInsertOptions.APPEND) {
            if (log.isDebugEnabled())
                log.debug("skipping user '" + getName() + "' (already defined)");
            return true;
        }// w  w  w .j  a  v a 2 s.  c o m
        Database.executeUpdate(conn, "UPDATE user SET password=?,active=? WHERE id=?;",
                UserManager.getPasswordEncryptor().encryptPassword(password.getValue()), active, userId);
        Database.executeUpdate(conn, "DELETE FROM user_definition WHERE object_id IS NULL AND user_id=?;",
                userId);
    } else {
        if (log.isDebugEnabled())
            log.debug("adding user '" + getName() + "'");
        userId = Database.addRecord(conn, "INSERT INTO user (name,uname,active,password) VALUES(?,?,?,?);",
                getName(), getName().toUpperCase(), active,
                UserManager.getPasswordEncryptor().encryptPassword(password.getValue()));
        if (userId == null)
            throw new InternalErrorException(Util.formatInternalErrorDescription("failed to insert user"));
        ctx.getUserIds().put(getName(), userId);
    }
    if (roles == null || roles.isEmpty())
        return true;
    if (log.isDebugEnabled())
        log.debug("saving user definition for '" + getName() + "'");
    final IErrorList<Integer> errors = ctx.getErrorList();
    final PreparedStatement stmt = conn
            .prepareStatement("INSERT INTO user_definition (user_id, role_id) VALUES(?,?);");
    try {
        stmt.setInt(1, userId);
        boolean success = true;
        for (XmlRoleName role : roles) {
            final Integer id = ctx.getRoleIds().get(role.getValue());
            if (id == null) {
                errors.add(role.getRow(), XmlRoleName.FIELD, CommonServerErrors.INVALID_VALUE);
                success = false;
            } else {
                stmt.setInt(2, id);
                stmt.addBatch();
            }
        }
        if (success && !Database.isBatchCompleted(stmt.executeBatch()))
            throw new InternalErrorException(
                    Util.formatInternalErrorDescription("failed to insert user definition"));
        return success;
    } finally {
        Database.close(stmt);
    }
}

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

@Test
public void testRestoreFromBinlog() throws Exception {
    MysqlReplicationApplier applier = null;
    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);
            pstmt.setInt(2, i);/*w  w w . j a  va  2  s .  c  om*/
            pstmt.execute();
        }

        // Copy the binlog somewhere
        Statement stmt = conn.createStatement();
        ResultSet rset = stmt.executeQuery("SHOW BINARY LOGS");
        rset.next();
        String binlogName = rset.getString("Log_name");
        rset = stmt.executeQuery("SELECT @@datadir");
        rset.next();
        String dataDir = rset.getString("@@datadir");
        File copyFile = new File(System.getProperty("java.io.tmpdir"),
                TestMysqlReplicationApplier.class.getName());
        FileUtils.copyFile(new File(dataDir + binlogName), copyFile);

        // Clear everything in MySQL
        resetMysql();

        // Get input stream, skipping and checking binlog magic number
        InputStream inputStream = new FileInputStream(copyFile);
        byte[] magic = new byte[MySQLConstants.BINLOG_MAGIC.length];
        int bytesRead = inputStream.read(magic);
        Assert.assertEquals(bytesRead, MySQLConstants.BINLOG_MAGIC.length);
        Assert.assertTrue(CodecUtils.equals(magic, MySQLConstants.BINLOG_MAGIC));

        // Restore from binlog
        PoolingDataSource<PoolableConnection> dataSource = getDataSource();
        applier = new MysqlReplicationApplier(inputStream, dataSource);
        ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
        });
        executorService.submit(applier);

        // Poll until we have restored
        long startTime = System.currentTimeMillis();
        long currentTime = startTime;
        do {
            stmt = conn.createStatement();
            rset = stmt.executeQuery("SELECT COUNT(*) FROM test.simple");
            rset.next();
            long count = rset.getLong(1);
            if (count == 10) {
                return;
            }
            Thread.sleep(1000);
            currentTime = System.currentTimeMillis();
        } while (currentTime - startTime < 10000);
    } finally {
        if (applier != null) {
            applier.shutdown();
        }
    }

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

From source file:net.sf.l2j.gameserver.model.entity.ClanHallSiege.java

public void setNewSiegeDate(long siegeDate, int ClanHallId, int hour) {
    Calendar tmpDate = Calendar.getInstance();
    if (siegeDate <= System.currentTimeMillis()) {
        tmpDate.setTimeInMillis(System.currentTimeMillis());
        tmpDate.add(Calendar.DAY_OF_MONTH, 3);
        tmpDate.set(Calendar.DAY_OF_WEEK, 6);
        tmpDate.set(Calendar.HOUR_OF_DAY, hour);
        tmpDate.set(Calendar.MINUTE, 0);
        tmpDate.set(Calendar.SECOND, 0);
        setSiegeDate(tmpDate);/*from ww w  .  jav a2s  . co m*/
        Connection con = null;
        try {
            con = L2DatabaseFactory.getInstance().getConnection();
            PreparedStatement statement = con
                    .prepareStatement("UPDATE clanhall_siege SET siege_data=? WHERE id = ?");
            statement.setLong(1, getSiegeDate().getTimeInMillis());
            statement.setInt(2, ClanHallId);
            statement.execute();
            statement.close();
        } catch (Exception e) {
            _log.error("Exception: can't save clanhall siege date: " + e.getMessage(), e);
        } finally {
            try {
                if (con != null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}