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:lineage2.gameserver.tables.ClanTable.java

/**
 * Method deleteClanFromDb.//from   ww  w.  j a  va2  s .  co m
 * @param clanId int
 */
public void deleteClanFromDb(int clanId) {
    long curtime = System.currentTimeMillis();
    Connection con = null;
    PreparedStatement statement = null;
    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement(
                "UPDATE characters SET clanid=0,title='',pledge_type=0,pledge_rank=0,lvl_joined_academy=0,apprentice=0,leaveclan=? WHERE clanid=?");
        statement.setLong(1, curtime / 1000L);
        statement.setInt(2, clanId);
        statement.execute();
        DbUtils.close(statement);
        statement = con.prepareStatement("DELETE FROM clan_data WHERE clan_id=?");
        statement.setInt(1, clanId);
        statement.execute();
        DbUtils.close(statement);
        statement = con.prepareStatement("DELETE FROM clan_subpledges WHERE clan_id=?");
        statement.setInt(1, clanId);
        statement.execute();
        DbUtils.close(statement);
        statement = con.prepareStatement("DELETE FROM clan_privs WHERE clan_id=?");
        statement.setInt(1, clanId);
        statement.execute();
        DbUtils.close(statement);
        statement = con.prepareStatement("DELETE FROM clan_skills WHERE clan_id=?");
        statement.setInt(1, clanId);
        statement.execute();
    } catch (Exception e) {
        _log.warn("could not dissolve clan:" + e);
    } finally {
        DbUtils.closeQuietly(con, statement);
    }
}

From source file:lineage2.gameserver.model.pledge.SubUnit.java

/**
 * Method setLeader./*  www . j  av a2 s  .c  om*/
 * @param newLeader UnitMember
 * @param updateDB boolean
 */
public void setLeader(UnitMember newLeader, boolean updateDB) {
    final UnitMember old = _leader;
    if (old != null) {
        old.setLeaderOf(Clan.SUBUNIT_NONE);
    }
    _leader = newLeader;
    _leaderObjectId = newLeader == null ? 0 : newLeader.getObjectId();
    if (newLeader != null) {
        newLeader.setLeaderOf(_type);
    }
    if (updateDB) {
        Connection con = null;
        PreparedStatement statement = null;
        try {
            con = DatabaseFactory.getInstance().getConnection();
            statement = con
                    .prepareStatement("UPDATE clan_subpledges SET leader_id=? WHERE clan_id=? and type=?");
            statement.setInt(1, getLeaderObjectId());
            statement.setInt(2, _clan.getClanId());
            statement.setInt(3, _type);
            statement.execute();
        } catch (Exception e) {
            _log.error("Exception: " + e, e);
        } finally {
            DbUtils.closeQuietly(con, statement);
        }
    }
}

From source file:com.l2jfree.gameserver.datatables.ItemTable.java

/**
 * Destroys the L2ItemInstance.<BR>
 * <BR>/*w w w . j  av a 2s . co m*/
 * <B><U> Actions</U> :</B><BR>
 * <BR>
 * <li>Sets L2ItemInstance parameters to be unusable </li>
 * <li>Removes the L2ItemInstance object to _allObjects of L2world </li>
 * <li>Logs Item delettion according to log settings</li>
 * <BR>
 * <BR>
 * 
 * @param process : String Identifier of process triggering this action
 * @param item : L2ItemInstance Item Identifier of the item to be created
 * @param actor : L2Player Player requesting the item destroy
 * @param reference : L2Object Object referencing current action like NPC selling item or previous item in
 *            transformation
 */
public void destroyItem(String process, L2ItemInstance item, L2Player actor, L2Object reference) {
    synchronized (item) {
        item.setCount(0);
        item.setOwnerId(0);
        item.setLocation(ItemLocation.VOID);
        item.setLastChange(L2ItemInstance.REMOVED);

        L2World.getInstance().removeObject(item);
        IdFactory.getInstance().releaseId(item.getObjectId());

        if (Config.LOG_ITEMS && actor != null) {
            List<Object> param = new ArrayList<Object>();
            param.add("DELETE:" + process);
            param.add(item);
            param.add(actor);
            param.add(reference);
            _logItems.info(param);
        }

        // if it's a pet control item, delete the pet as well
        if (PetDataTable.isPetItem(item.getItemId())) {
            Connection con = null;
            try {
                // Delete the pet in db
                con = L2DatabaseFactory.getInstance().getConnection(con);
                PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?");
                statement.setInt(1, item.getObjectId());
                statement.execute();
                statement.close();
            } catch (Exception e) {
                _log.warn("could not delete pet objectid:", e);
            } finally {
                L2DatabaseFactory.close(con);
            }
        }

        // delete augmentation data
        item.removeAugmentation();
    }
}

From source file:com.talkdesk.geo.GeoCodeRepositoryBuilder.java

/**
 * Format of the file loading data from//from   ww w .  j  a va2  s  .  c o  m
 * geonameid         : integer id of record in geonames database
 * name              : name of geographical point (utf8) varchar(200)
 * asciiname         : name of geographical point in plain ascii characters, varchar(200)
 * alternatenames    : alternatenames, comma separated, ascii names automatically transliterated, convenience attribute from alternatename table, varchar(10000)
 * latitude          : latitude in decimal degrees (wgs84)
 * longitude         : longitude in decimal degrees (wgs84)
 * feature class     : see http://www.geonames.org/export/codes.html, char(1)
 * feature code      : see http://www.geonames.org/export/codes.html, varchar(10)
 * country code      : ISO-3166 2-letter country code, 2 characters
 * cc2               : alternate country codes, comma separated, ISO-3166 2-letter country code, 60 characters
 * admin1 code       : fipscode (subject to change to iso code), see exceptions below, see file admin1Codes.txt for display names of this code; varchar(20)
 * admin2 code       : code for the second administrative division, a county in the US, see file admin2Codes.txt; varchar(80)
 * admin3 code       : code for third level administrative division, varchar(20)
 * admin4 code       : code for fourth level administrative division, varchar(20)
 * population        : bigint (8 byte int)
 * elevation         : in meters, integer
 * dem               : digital elevation model, srtm3 or gtopo30, average elevation of 3''x3'' (ca 90mx90m) or 30''x30'' (ca 900mx900m) area in meters, integer. srtm processed by cgiar/ciat.
 * timezone          : the timezone id (see file timeZone.txt) varchar(40)
 * modification date : date of last modification in yyyy-MM-dd format
 *
 * @throws IOException
 */
public void populateGeoData() throws GeoResolverException {

    try {
        if (connection == null)
            connection = connectToDatabase();
        if (!new File(geocodeDataLocation).exists()) {
            log.error("No Data file found for geoData. please add to data/geodata.tsv ");
            return;
        }

        Path file = FileSystems.getDefault().getPath(geocodeDataLocation);
        Charset charset = Charset.forName("UTF-8");
        BufferedReader inputStream = Files.newBufferedReader(file, charset);
        String buffer;
        PreparedStatement preparedStatement;
        preparedStatement = connection
                .prepareStatement("INSERT INTO geocodes (ID , CITY_NAME, LATITUDE, LONGITUDE, COUNTRY_CODE)"
                        + " VALUES (?,?,?,?,?)");
        while ((buffer = inputStream.readLine()) != null) {
            String[] values = buffer.split("\t");

            preparedStatement.setInt(1, Integer.parseInt(values[0].trim()));
            preparedStatement.setString(2, values[1].trim());
            preparedStatement.setFloat(3, Float.parseFloat(values[4].trim()));
            preparedStatement.setFloat(4, Float.parseFloat(values[5].trim()));
            preparedStatement.setString(5, values[8].trim());

            preparedStatement.execute();

        }
    } catch (SQLException e) {
        throw new GeoResolverException("Error while executing SQL query", e);
    } catch (IOException e) {
        throw new GeoResolverException("Error while accessing input file", e);
    }
    log.info("Finished populating Database.");
    //should close all the connections for memory leaks.
}

From source file:com.chaosinmotion.securechat.server.commands.ChangePassword.java

public static boolean processRequest(Login.UserInfo userinfo, JSONObject requestParams, String token)
        throws ClassNotFoundException, SQLException, IOException {
    String oldpassword = requestParams.optString("oldpassword");
    String newpassword = requestParams.optString("newpassword");

    /*/*  w  ww. j av  a2 s .  c o  m*/
     * Validate the old password against the token we received
     */

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        c = Database.get();
        ps = c.prepareStatement("SELECT password " + "FROM Users " + "WHERE userid = ?");
        ps.setInt(1, userinfo.getUserID());
        rs = ps.executeQuery();

        if (rs.next()) {
            /*
             * If the result is found, hash the entry in the way it would
             * be hashed by the front end, and compare to see if the
             * hash codes match. (This requires that the hashed password
             * stored in the back-end has a consistent capitalization.
             * We arbitrarily pick lower-case for our SHA-256 hex string.
             */
            String spassword = rs.getString(1);

            /*
             * Encrypt password with token and salt
             */

            spassword = spassword + Constants.SALT + token;
            spassword = Hash.sha256(spassword);

            /*
             * Compare; if matches, then return the user info record
             * so we can store away. While the SHA256 process returns
             * consistent case, we compare ignoring case anyway, just
             * because. :-)
             */

            if (!spassword.equalsIgnoreCase(oldpassword)) {
                /* Wrong password */
                return false;
            }
        }

        /*
         * Update password stored with the updated value passed in.
         */

        rs.close();
        ps.close();

        ps = c.prepareStatement("UPDATE Users " + "SET password = ? " + "WHERE userid = ?");
        ps.setString(1, newpassword);
        ps.setInt(2, userinfo.getUserID());
        ps.execute();

        return true;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testDateTimeTimestampWithCalendar() throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("create table ts(x timestamp primary key)");
    stat.execute("create table t(x time primary key)");
    stat.execute("create table d(x date)");
    Calendar utcCalendar = new GregorianCalendar(new SimpleTimeZone(0, "Z"));
    TimeZone old = TimeZone.getDefault();
    DateTimeUtils.resetCalendar();/*from ww w.ja  v  a  2  s  .c om*/
    TimeZone.setDefault(TimeZone.getTimeZone("PST"));
    try {
        Timestamp ts1 = Timestamp.valueOf("2010-03-13 18:15:00");
        Time t1 = new Time(ts1.getTime());
        Date d1 = new Date(ts1.getTime());
        // when converted to UTC, this is 03:15, which doesn't actually exist
        // because of summer time change at that day
        Timestamp ts2 = Timestamp.valueOf("2010-03-13 19:15:00");
        Time t2 = new Time(ts2.getTime());
        Date d2 = new Date(ts2.getTime());
        PreparedStatement prep;
        ResultSet rs;
        prep = conn.prepareStatement("insert into ts values(?)");
        prep.setTimestamp(1, ts1, utcCalendar);
        prep.execute();
        prep.setTimestamp(1, ts2, utcCalendar);
        prep.execute();
        prep = conn.prepareStatement("insert into t values(?)");
        prep.setTime(1, t1, utcCalendar);
        prep.execute();
        prep.setTime(1, t2, utcCalendar);
        prep.execute();
        prep = conn.prepareStatement("insert into d values(?)");
        prep.setDate(1, d1, utcCalendar);
        prep.execute();
        prep.setDate(1, d2, utcCalendar);
        prep.execute();
        rs = stat.executeQuery("select * from ts order by x");
        rs.next();
        assertEquals("2010-03-14 02:15:00.0", rs.getString(1));
        assertEquals("2010-03-13 18:15:00.0", rs.getTimestamp(1, utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp(1).toString());
        assertEquals("2010-03-14 02:15:00.0", rs.getString("x"));
        assertEquals("2010-03-13 18:15:00.0", rs.getTimestamp("x", utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp("x").toString());
        rs.next();
        assertEquals("2010-03-14 03:15:00.0", rs.getString(1));
        assertEquals("2010-03-13 19:15:00.0", rs.getTimestamp(1, utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp(1).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getString("x"));
        assertEquals("2010-03-13 19:15:00.0", rs.getTimestamp("x", utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp("x").toString());
        rs = stat.executeQuery("select * from t order by x");
        rs.next();
        assertEquals("02:15:00", rs.getString(1));
        assertEquals("18:15:00", rs.getTime(1, utcCalendar).toString());
        assertEquals("02:15:00", rs.getTime(1).toString());
        assertEquals("02:15:00", rs.getString("x"));
        assertEquals("18:15:00", rs.getTime("x", utcCalendar).toString());
        assertEquals("02:15:00", rs.getTime("x").toString());
        rs.next();
        assertEquals("03:15:00", rs.getString(1));
        assertEquals("19:15:00", rs.getTime(1, utcCalendar).toString());
        assertEquals("03:15:00", rs.getTime(1).toString());
        assertEquals("03:15:00", rs.getString("x"));
        assertEquals("19:15:00", rs.getTime("x", utcCalendar).toString());
        assertEquals("03:15:00", rs.getTime("x").toString());
        rs = stat.executeQuery("select * from d order by x");
        rs.next();
        assertEquals("2010-03-14", rs.getString(1));
        assertEquals("2010-03-13", rs.getDate(1, utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate(1).toString());
        assertEquals("2010-03-14", rs.getString("x"));
        assertEquals("2010-03-13", rs.getDate("x", utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate("x").toString());
        rs.next();
        assertEquals("2010-03-14", rs.getString(1));
        assertEquals("2010-03-13", rs.getDate(1, utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate(1).toString());
        assertEquals("2010-03-14", rs.getString("x"));
        assertEquals("2010-03-13", rs.getDate("x", utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate("x").toString());
    } finally {
        TimeZone.setDefault(old);
        DateTimeUtils.resetCalendar();
    }
    stat.execute("drop table ts");
    stat.execute("drop table t");
    stat.execute("drop table d");
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

public <T> void deleteRecord(Class<T> kind, String fieldName, Object keyValue)
        throws SQLException, WPBSerializerException {
    Connection connection = getConnection();
    PreparedStatement preparedStatement = null;
    try {/*from w ww.  ja  va  2 s.co m*/
        String sqlStatement = getSQLStringForDelete(kind, fieldName);
        connection.setAutoCommit(true);
        preparedStatement = connection.prepareStatement(sqlStatement);
        setPrepareStatementParameter(preparedStatement, 1, keyValue);

        preparedStatement.execute();
    } catch (SQLException e) {
        throw e;
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        connection.close();
    }
}

From source file:com.tesora.dve.common.DBHelper.java

private boolean executePrepared(PreparedStatement ps, String query, List<Object> params)
        throws SQLException, PEException {

    if (ps == null) {
        throw new PEException("A prepared statement is not available to be executed - call prepare first");
    }//  w  ww. j  ava 2  s.  c  o  m

    if (logger.isDebugEnabled() && query != null)
        logger.debug("Command: " + query);

    for (int i = 0; i < params.size(); i++) {
        ps.setObject(i + 1, params.get(i));
    }

    boolean ret = ps.execute();
    if (!ret) {
        // when stmt.execute returns false it means no result set is
        // expected get the number of rows affected
        rowCount = ps.getUpdateCount();

        printLine(rowCount + " rows affected");

    } else {
        // a prepStmt returning a result set was run
        resultSet = ps.getResultSet();
        if (useBufferedQuery)
            resultSet.setFetchSize(Integer.MAX_VALUE);
    }
    return ret;

}

From source file:lineage2.gameserver.model.entity.Hero.java

/**
 * Method saveHeroMessage.// www.ja  v a2s . c om
 * @param charId int
 */
public void saveHeroMessage(int charId) {
    if (_heroMessage.get(charId) == null) {
        return;
    }
    Connection con = null;
    PreparedStatement statement = null;
    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement("UPDATE heroes SET message=? WHERE char_id=?;");
        statement.setString(1, _heroMessage.get(charId));
        statement.setInt(2, charId);
        statement.execute();
        statement.close();
    } catch (SQLException e) {
        _log.error("SQL exception while saving HeroMessage.", e);
    } finally {
        DbUtils.closeQuietly(con, statement);
    }
}

From source file:com.moss.schematrax.SchemaUpdater.java

private void recordUpdate(Connection sqlConnection, String schema, SchemaUpdate update) throws SQLException {
    PreparedStatement preparedStatement = sqlConnection
            .prepareStatement("INSERT INTO " + schema + ".SCHEMA_UPDATES values (?,?)");
    preparedStatement.setString(1, update.getId());
    preparedStatement.setTimestamp(2, new java.sql.Timestamp(new Date().getTime()));
    preparedStatement.execute();
    if (manageTransactions)
        sqlConnection.commit();/* w w  w  .j a v a2s.c om*/
}