Example usage for java.sql ResultSet getDouble

List of usage examples for java.sql ResultSet getDouble

Introduction

In this page you can find the example usage for java.sql ResultSet getDouble.

Prototype

double getDouble(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language.

Usage

From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java

@Override
public Item addWatch(final Watch watch) {
    Item obj = null;/*from  w  w  w  . j av a2 s. c o m*/

    Connection conn = null;
    CallableStatement stmt = null;
    ResultSet rs = null;

    try {
        conn = _dataSource.getConnection();

        stmt = conn.prepareCall("{call SP_EDITWATCH (?,?,?)}");
        stmt.registerOutParameter(1, Types.INTEGER);
        stmt.setInt(2, watch.getItemUid());
        stmt.setInt(3, watch.getUserUid());

        stmt.execute();
        stmt.close(); // close statement to prevent leak

        stmt = conn.prepareCall("{call SP_GETITEM (?)}");
        stmt.setInt(1, watch.getItemUid());

        rs = stmt.executeQuery();

        if (rs.next()) {
            ItemBuilder builder = Item.newBuilder().setUid(rs.getInt("UID"))
                    .setAuctionUid(rs.getInt("AUCTIONUID")).setItemNumber(rs.getString("ITEMNUMBER"))
                    .setName(rs.getString("NAME")).sertCurPrice(rs.getDouble("CURPRICE"))
                    .setWinner(rs.getString("WINNER")).setBidCount(rs.getInt("BIDCOUNT"))
                    .setWatchCount(rs.getInt("WATCHCOUNT"));

            obj = builder.build();
        }
    } catch (SQLException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } finally {
        DbUtils.closeQuietly(conn, stmt, rs);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("WATCH [method:{} result:{}]",
                new Object[] { "add", obj != null ? obj.toString() : "[error]" });
    }

    return obj;
}

From source file:com.concursive.connect.web.modules.profile.dao.ProjectIndexer.java

/**
 * Given a database and an indexer, this method will add content to the
 * searchable index//from  w  w w  .ja  va 2s  .com
 *
 * @param writer  Description of the Parameter
 * @param db      Description of the Parameter
 * @param context Servlet context
 * @throws SQLException Description of the Exception
 * @throws IOException  Description of the Exception
 */
public void add(IIndexerService writer, Connection db, IndexerContext context) throws Exception {
    long startTime = System.currentTimeMillis();
    int count = 0;
    PreparedStatement pst = db.prepareStatement(
            "SELECT instance_id, project_id, title, shortdescription, description, requestedby, requesteddept, entered, modified, "
                    + "category_id, subcategory1_id, "
                    + "allow_guests, membership_required, allows_user_observers, approvaldate, closedate, portal, "
                    + "city, state, postalcode, keywords, " + "rating_count, rating_value, rating_avg "
                    + "FROM projects " + "WHERE project_id > -1 ");
    ResultSet rs = pst.executeQuery();
    while (rs.next() && context.getEnabled()) {
        ++count;
        // read the record
        Project project = new Project();
        project.setInstanceId(rs.getInt("instance_id"));
        project.setId(rs.getInt("project_id"));
        project.setTitle(rs.getString("title"));
        project.setShortDescription(rs.getString("shortdescription"));
        project.setDescription(rs.getString("description"));
        project.setRequestedBy(rs.getString("requestedby"));
        project.setRequestedByDept(rs.getString("requesteddept"));
        project.setEntered(rs.getTimestamp("entered"));
        project.setModified(rs.getTimestamp("modified"));
        project.setCategoryId(DatabaseUtils.getInt(rs, "category_id"));
        project.setSubCategory1Id(DatabaseUtils.getInt(rs, "subcategory1_id"));
        project.getFeatures().setAllowGuests(rs.getBoolean("allow_guests"));
        project.getFeatures().setMembershipRequired(rs.getBoolean("membership_required"));
        project.getFeatures().setAllowParticipants(rs.getBoolean("allows_user_observers"));
        project.setApprovalDate(rs.getTimestamp("approvaldate"));
        if (project.getApprovalDate() != null) {
            project.setApproved(true);
        }
        project.setCloseDate(rs.getTimestamp("closedate"));
        if (project.getCloseDate() != null) {
            project.setClosed(true);
        }
        project.setPortal(rs.getBoolean("portal"));
        project.setCity(rs.getString("city"));
        project.setState(rs.getString("state"));
        project.setPostalCode(rs.getString("postalcode"));
        project.setKeywords(rs.getString("keywords"));
        project.setRatingCount(rs.getInt("rating_count"));
        project.setRatingValue(rs.getInt("rating_value"));
        project.setRatingAverage((rs.getDouble("rating_avg")));
        // add the document
        if (writer instanceof LuceneIndexer) {
            LuceneIndexer luceneWriter = (LuceneIndexer) writer;
            luceneWriter.indexAddItem(project, false, context.getIndexType());
        } else {
            // Don't know specifically what to do...
            writer.indexAddItem(project, false);
        }
    }
    rs.close();
    pst.close();
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    LOG.info("Finished: " + count + " took " + totalTime + " ms");
}

From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java

@Override
public List<Item> getItems(final int auctionUid, final int categoryuid, final int start, final int length,
        final String sort, final String dir) {
    List<Item> objs = Lists.newArrayList();

    Connection conn = null;//  ww  w. java2 s  .  c o m
    CallableStatement stmt = null;
    ResultSet rs = null;

    try {
        conn = _dataSource.getConnection();

        stmt = conn.prepareCall("{call SP_GETITEMS (?,?,?,?,?,?)}");
        stmt.setInt(1, auctionUid);
        stmt.setInt(2, categoryuid);
        stmt.setInt(3, start);
        stmt.setInt(4, length);
        stmt.setString(5, sort);
        stmt.setString(6, dir);

        rs = stmt.executeQuery();

        while (rs.next()) {
            ItemBuilder builder = Item.newBuilder().setUid(rs.getInt("UID"))
                    .setAuctionUid(rs.getInt("AUCTIONUID")).setItemNumber(rs.getString("ITEMNUMBER"))
                    .setName(rs.getString("NAME")).setDescription(rs.getString("DESCRIPTION"))
                    .setCategory(rs.getString("CATEGORY")).setSeller(rs.getString("SELLER"))
                    .setValPrice(rs.getDouble("VALPRICE")).setMinPrice(rs.getDouble("MINPRICE"))
                    .setIncPrice(rs.getDouble("INCPRICE")).sertCurPrice(rs.getDouble("CURPRICE"))
                    .setWinner(rs.getString("WINNER")).setBidCount(rs.getInt("BIDCOUNT"))
                    .setWatchCount(rs.getInt("WATCHCOUNT")).setUrl(rs.getString("URL"))
                    .setMultiSale(rs.getBoolean("MULTI"));

            objs.add(builder.build());
        }
    } catch (SQLException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } finally {
        DbUtils.closeQuietly(conn, stmt, rs);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("ITEM [method:{} result:{}]", new Object[] { "get", objs.size() });
    }

    return ImmutableList.copyOf(objs);
}

From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java

@Override
public Item addBid(final Bid bid) {
    Item obj = null;//from   ww  w.  j  a  va2 s.  c  o  m

    Connection conn = null;
    CallableStatement stmt = null;
    ResultSet rs = null;

    try {
        conn = _dataSource.getConnection();

        stmt = conn.prepareCall("{call SP_EDITBID (?,?,?,?)}");
        stmt.registerOutParameter(1, Types.INTEGER);
        stmt.setInt(2, bid.getItemUid());
        stmt.setInt(3, bid.getUserUid());
        stmt.setDouble(4, bid.getBidPrice());

        stmt.execute();
        stmt.close(); // close statement to prevent leak

        stmt = conn.prepareCall("{call SP_GETITEM (?)}");
        stmt.setInt(1, bid.getItemUid());

        rs = stmt.executeQuery();

        if (rs.next()) {
            ItemBuilder builder = Item.newBuilder().setUid(rs.getInt("UID"))
                    .setAuctionUid(rs.getInt("AUCTIONUID")).setItemNumber(rs.getString("ITEMNUMBER"))
                    .setName(rs.getString("NAME")).sertCurPrice(rs.getDouble("CURPRICE"))
                    .setWinner(rs.getString("WINNER")).setBidCount(rs.getInt("BIDCOUNT"))
                    .setWatchCount(rs.getInt("WATCHCOUNT"));

            obj = builder.build();
        }
    } catch (SQLException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } finally {
        DbUtils.closeQuietly(conn, stmt, rs);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("BID [method:{} result:{}]",
                new Object[] { "add", obj != null ? obj.toString() : "[error]" });
    }

    return obj;
}

From source file:fll.db.Queries.java

/**
 * Process the team rankings from the executed query. It is assumed that the
 * query returns first an int that is the team number and then a double that
 * is the score. <code>teamMap</code> is populated with the data. The
 * ResultSet is closed by this function.
 *//*from w  w w  .ja va 2s  .co m*/
private static void processTeamRankings(final Map<Integer, TeamRanking> teamRankings,
        final String categoryTitle, final String rankingGroup, final ResultSet rs) throws SQLException {
    final List<Integer> ranks = new LinkedList<Integer>();
    final List<Integer> teams = new LinkedList<Integer>();

    int numTeams = 0;
    int tieRank = 1;
    int rank = 1;
    double prevScore = Double.NaN;
    while (rs.next()) {
        final int team = rs.getInt(1);
        double score = rs.getDouble(2);
        teams.add(team);
        if (rs.wasNull()) {
            ranks.add(CategoryRank.NO_SHOW_RANK);
        } else if (Math.abs(score - prevScore) < 0.001) {
            // 3 decimal places should be considered equal
            ranks.add(tieRank);
        } else {
            tieRank = rank;
            ranks.add(rank);
        }

        // setup for next round
        prevScore = score;

        // increment rank counter
        ++rank;
        ++numTeams;
    } // end score group rank

    for (int i = 0; i < ranks.size(); ++i) {
        final CategoryRank catRank = new CategoryRank(rankingGroup, categoryTitle, ranks.get(i), numTeams);
        TeamRanking teamRank = teamRankings.get(teams.get(i));
        if (null == teamRank) {
            teamRank = new TeamRanking(teams.get(i));
            teamRankings.put(teams.get(i), teamRank);
        }
        teamRank.setRankForCategory(categoryTitle, catRank);
    }

    SQLFunctions.close(rs);
}

From source file:net.tourbook.tour.photo.TourPhotoManager.java

@Override
public void setTourReference(final Photo photo) {

    //      final long start = System.nanoTime();

    Connection conn = null;/*from  w  w  w . j av a 2 s .  co  m*/

    try {

        conn = TourDatabase.getInstance().getConnection();

        final String sql = "SELECT " //                                                 //$NON-NLS-1$
                //
                + " photoId, " //                                 1 //$NON-NLS-1$
                + (" " + TourDatabase.TABLE_TOUR_DATA + "_tourId, ") //    2 //$NON-NLS-1$ //$NON-NLS-2$
                //
                + " adjustedTime, " //                              3 //$NON-NLS-1$
                + " imageExifTime, " //                              4 //$NON-NLS-1$
                + " latitude, " //                                 5 //$NON-NLS-1$
                + " longitude, " //                                 6 //$NON-NLS-1$
                + " isGeoFromPhoto, " //                           7 //$NON-NLS-1$
                + " ratingStars " //                              8 //$NON-NLS-1$
                //
                + " FROM " + TourDatabase.TABLE_TOUR_PHOTO //            //$NON-NLS-1$
                //
                + " WHERE imageFilePathName=?"; //                     //$NON-NLS-1$

        final PreparedStatement stmt = conn.prepareStatement(sql);

        stmt.setString(1, photo.imageFilePathName);

        final ResultSet result = stmt.executeQuery();

        while (result.next()) {

            final long dbPhotoId = result.getLong(1);
            final long dbTourId = result.getLong(2);

            final long dbAdjustedTime = result.getLong(3);
            final long dbImageExifTime = result.getLong(4);
            final double dbLatitude = result.getDouble(5);
            final double dbLongitude = result.getDouble(6);
            final int dbIsGeoFromExif = result.getInt(7);
            final int dbRatingStars = result.getInt(8);

            photo.addTour(dbTourId, dbPhotoId);

            /*
             * when a photo is in the photo cache it is possible that the tour is from the file
             * system, update tour relevant fields
             */

            photo.isSavedInTour = true;

            photo.adjustedTimeTour = dbAdjustedTime;
            photo.imageExifTime = dbImageExifTime;

            photo.isGeoFromExif = dbIsGeoFromExif == 1;
            photo.isTourPhotoWithGps = dbLatitude != 0;

            photo.ratingStars = dbRatingStars;

            if (photo.getTourLatitude() == 0 && dbLatitude != 0) {
                photo.setTourGeoPosition(dbLatitude, dbLongitude);
            }

            PhotoCache.setPhoto(photo);
        }

    } catch (final SQLException e) {
        net.tourbook.ui.UI.showSQLException(e);
    } finally {

        if (conn != null) {
            try {
                conn.close();
            } catch (final SQLException e) {
                net.tourbook.ui.UI.showSQLException(e);
            }
        }
    }

    //      System.out.println(net.tourbook.common.UI.timeStampNano()
    //            + " load sql tourId from photo\t"
    //            + ((float) (System.nanoTime() - start) / 1000000)
    //            + " ms");
    // TODO remove SYSTEM.OUT.PRINTLN
}

From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java

/**
 * Populates the object's properties from the result set
 *
 * @param rs        Description of Parameter
 * @param isVersion Description of Parameter
 * @throws SQLException Description of Exception
 *//*from  w w w .  ja  v  a 2s  .c  o  m*/
protected void buildRecord(ResultSet rs, boolean isVersion) throws SQLException {
    id = rs.getInt("item_id");
    if (!isVersion) {
        linkModuleId = rs.getInt("link_module_id");
        linkItemId = rs.getInt("link_item_id");
        folderId = DatabaseUtils.getInt(rs, "folder_id", -1);
    }
    clientFilename = rs.getString("client_filename");
    filename = rs.getString("filename");
    subject = rs.getString("subject");
    size = rs.getInt("size");
    version = rs.getDouble("version");
    enabled = rs.getBoolean("enabled");
    downloads = rs.getInt("downloads");
    entered = rs.getTimestamp("entered");
    enteredBy = rs.getInt("enteredby");
    modified = rs.getTimestamp("modified");
    modifiedBy = rs.getInt("modifiedby");
    if (!isVersion) {
        thumbnailFilename = rs.getString("thumbnail");
    }
    defaultFile = rs.getBoolean("default_file");
    imageWidth = rs.getInt("image_width");
    imageHeight = rs.getInt("image_height");
    comment = rs.getString("comment");
    featuredFile = rs.getBoolean("featured_file");
    ratingCount = DatabaseUtils.getInt(rs, "rating_count", 0);
    ratingValue = DatabaseUtils.getInt(rs, "rating_value", 0);
    ratingAvg = DatabaseUtils.getDouble(rs, "rating_avg", 0.0);
    inappropriateCount = DatabaseUtils.getInt(rs, "inappropriate_count", 0);
}

From source file:com.p000ison.dev.simpleclans2.converter.Converter.java

public void convertClans() throws SQLException {
    ResultSet result = from.query("SELECT * FROM `sc_clans`;");

    while (result.next()) {
        JSONObject flags = new JSONObject();

        String name = result.getString("name");
        String tag = result.getString("tag");
        boolean verified = result.getBoolean("verified");
        boolean friendly_fire = result.getBoolean("friendly_fire");
        long founded = result.getLong("founded");
        long last_used = result.getLong("last_used");
        String flagsString = result.getString("flags");
        String cape = result.getString("cape_url");

        ConvertedClan clan = new ConvertedClan(tag);
        clan.setPackedAllies(result.getString("packed_allies"));
        clan.serPackedRivals(result.getString("packed_rivals"));

        if (friendly_fire) {
            flags.put("ff", friendly_fire);
        }/*w  w w.  ja  v  a  2  s . c o m*/

        if (cape != null && !cape.isEmpty()) {
            flags.put("cape-url", cape);
        }

        JSONParser parser = new JSONParser();
        try {
            JSONObject object = (JSONObject) parser.parse(flagsString);
            String world = object.get("homeWorld").toString();
            if (!world.isEmpty()) {
                int x = ((Long) object.get("homeX")).intValue();
                int y = ((Long) object.get("homeY")).intValue();
                int z = ((Long) object.get("homeZ")).intValue();

                flags.put("home", x + ":" + y + ":" + z + ":" + world + ":0:0");
            }

            clan.setRawWarring((JSONArray) object.get("warring"));
        } catch (ParseException e) {
            Logging.debug(e, true);
            continue;
        }

        insertClan(name, tag, verified, founded, last_used, flags.isEmpty() ? null : flags.toJSONString(),
                result.getDouble("balance"));

        String selectLastQuery = "SELECT `id` FROM `sc2_clans` ORDER BY ID DESC LIMIT 1;";

        ResultSet selectLast = to.query(selectLastQuery);
        selectLast.next();
        clan.setId(selectLast.getLong("id"));
        selectLast.close();

        insertBB(Arrays.asList(result.getString("packed_bb").split("\\s*(\\||$)")), clan.getId());

        clans.add(clan);
    }

    for (ConvertedClan clan : clans) {
        JSONArray allies = new JSONArray();
        JSONArray rivals = new JSONArray();
        JSONArray warring = new JSONArray();

        for (String allyTag : clan.getRawAllies()) {
            long allyID = getIDByTag(allyTag);
            if (allyID != -1) {
                allies.add(allyID);
            }
        }

        for (String rivalTag : clan.getRawAllies()) {
            long rivalID = getIDByTag(rivalTag);
            if (rivalID != -1) {
                rivals.add(rivalID);
            }
        }

        for (String warringTag : clan.getRawWarring()) {
            long warringID = getIDByTag(warringTag);
            if (warringID != -1) {
                warring.add(warringID);
            }
        }

        if (!allies.isEmpty()) {
            updateClan.setString(1, allies.toJSONString());
        } else {
            updateClan.setNull(1, Types.VARCHAR);
        }

        if (!rivals.isEmpty()) {
            updateClan.setString(2, rivals.toJSONString());
        } else {
            updateClan.setNull(2, Types.VARCHAR);
        }

        if (!warring.isEmpty()) {
            updateClan.setString(3, warring.toJSONString());
        } else {
            updateClan.setNull(3, Types.VARCHAR);
        }

        updateClan.setLong(4, clan.getId());
        updateClan.executeUpdate();
    }
}

From source file:com.greatmancode.craftconomy3.utils.OldFormatConverter.java

public void run() throws SQLException, IOException, ParseException {
    String dbType = Common.getInstance().getMainConfig().getString("System.Database.Type");
    HikariConfig config = new HikariConfig();
    if (dbType.equalsIgnoreCase("mysql")) {
        config.setMaximumPoolSize(10);//w w w.j av a  2 s .  c o  m
        config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
        config.addDataSourceProperty("serverName",
                Common.getInstance().getMainConfig().getString("System.Database.Address"));
        config.addDataSourceProperty("port",
                Common.getInstance().getMainConfig().getString("System.Database.Port"));
        config.addDataSourceProperty("databaseName",
                Common.getInstance().getMainConfig().getString("System.Database.Db"));
        config.addDataSourceProperty("user",
                Common.getInstance().getMainConfig().getString("System.Database.Username"));
        config.addDataSourceProperty("password",
                Common.getInstance().getMainConfig().getString("System.Database.Password"));
        config.addDataSourceProperty("autoDeserialize", true);
        config.setConnectionTimeout(5000);
        db = new HikariDataSource(config);

    } else if (dbType.equalsIgnoreCase("sqlite")) {
        config.setDriverClassName("org.sqlite.JDBC");
        config.setJdbcUrl("jdbc:sqlite:" + Common.getInstance().getServerCaller().getDataFolder()
                + File.separator + "database.db");
        db = new HikariDataSource(config);
    } else {
        Common.getInstance().sendConsoleMessage(Level.SEVERE,
                "Unknown database type for old format converter!");
        return;
    }
    Connection connection = db.getConnection();
    this.tablePrefix = Common.getInstance().getMainConfig().getString("System.Database.Prefix");

    File accountFile = new File(Common.getInstance().getServerCaller().getDataFolder(), "accounts.json");

    Common.getInstance().sendConsoleMessage(Level.INFO,
            "Doing a backup in a xml file before doing the conversion.");
    //Document setup
    JSONObject mainObject = new JSONObject();

    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving currency table");
    //Currencies
    PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "currency");
    ResultSet set = statement.executeQuery();
    JSONArray array = new JSONArray();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("id", set.getInt("id"));
        entry.put("name", set.getString("name"));
        entry.put("plural", set.getString("plural"));
        entry.put("minor", set.getString("minor"));
        entry.put("minorPlural", set.getString("minorPlural"));
        entry.put("sign", set.getString("sign"));
        entry.put("status", set.getBoolean("status"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("currencies", array);

    //World groups
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving world group table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "worldgroup");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("groupName", set.getString("groupName"));
        entry.put("worldList", set.getString("worldList"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("worldgroups", array);

    //Exchange table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving exchange table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "exchange");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("from_currency_id", set.getInt("from_currency_id"));
        entry.put("to_currency_id", set.getInt("to_currency_id"));
        entry.put("amount", set.getDouble("amount"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("exchanges", array);

    //config table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving config table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "config");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("name", set.getString("name"));
        entry.put("value", set.getString("value"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("configs", array);

    //account table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving account table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "account");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("name", set.getString("name"));
        entry.put("infiniteMoney", set.getBoolean("infiniteMoney"));
        entry.put("ignoreACL", set.getBoolean("ignoreACL"));
        entry.put("uuid", set.getString("uuid"));

        JSONArray balanceArray = new JSONArray();
        PreparedStatement internalStatement = connection
                .prepareStatement("SELECT * FROM " + tablePrefix + "balance WHERE username_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        ResultSet internalSet = internalStatement.executeQuery();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("currency_id", internalSet.getInt("currency_id"));
            object.put("worldName", internalSet.getString("worldName"));
            object.put("balance", internalSet.getDouble("balance"));
            balanceArray.add(object);
        }
        internalStatement.close();
        entry.put("balances", balanceArray);

        internalStatement = connection
                .prepareStatement("SELECT * FROM " + tablePrefix + "log WHERE username_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        internalSet = internalStatement.executeQuery();
        JSONArray logArray = new JSONArray();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("type", internalSet.getObject("type"));
            object.put("cause", internalSet.getObject("cause"));
            object.put("timestamp", internalSet.getTimestamp("timestamp"));
            object.put("causeReason", internalSet.getString("causeReason"));
            object.put("currencyName", internalSet.getString("currencyName"));
            object.put("worldName", internalSet.getString("worldName"));
            object.put("amount", internalSet.getDouble("amount"));
            logArray.add(object);
        }
        internalStatement.close();
        entry.put("logs", logArray);

        internalStatement = connection
                .prepareStatement("SELECT * FROM " + tablePrefix + "acl WHERE account_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        internalSet = internalStatement.executeQuery();
        JSONArray aclArray = new JSONArray();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("playerName", internalSet.getString("playerName"));
            object.put("deposit", internalSet.getBoolean("deposit"));
            object.put("withdraw", internalSet.getBoolean("withdraw"));
            object.put("acl", internalSet.getBoolean("acl"));
            object.put("balance", internalSet.getBoolean("balance"));
            object.put("owner", internalSet.getBoolean("owner"));
            aclArray.add(object);

        }
        internalStatement.close();
        entry.put("acls", aclArray);
        array.add(entry);
    }
    statement.close();
    mainObject.put("accounts", array);
    Common.getInstance().sendConsoleMessage(Level.INFO, "Writing json file");
    FileWriter writer = new FileWriter(accountFile);
    writer.write(mainObject.toJSONString());
    writer.flush();
    writer.close();
    Common.getInstance().sendConsoleMessage(Level.INFO, "File written! Dropping all tables");
    //The backup is now saved. Let's drop everything
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "config");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "acl");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "balance");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "log");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "worldgroup");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "exchange");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "account");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "currency");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "payday");
    statement.execute();
    statement.close();

    connection.close();
    step2();

}

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

/**
 * Returns object Item from the record of the database
 * //w  ww .  j a va2s.c o  m
 * @param rset : ResultSet designating a record of the [weapon] table of database
 * @return Item : object created from the database record
 * @throws SQLException
 */
private Item readWeapon(ResultSet rset, boolean custom) throws SQLException {
    Item item = new Item();
    item.set = new StatsSet();
    item.type = _weaponTypes.get(rset.getString("weaponType"));
    item.id = rset.getInt("item_id");
    item.displayid = custom ? rset.getInt("item_display_id") : item.id;
    item.name = rset.getString("name");

    item.set.set("item_id", item.id);
    item.set.set("item_display_id", item.displayid);
    item.set.set("name", item.name);

    // lets see if this is a shield
    if (item.type == L2WeaponType.NONE) {
        item.set.set("type1", L2Item.TYPE1_SHIELD_ARMOR);
        item.set.set("type2", L2Item.TYPE2_SHIELD_ARMOR);
    } else {
        item.set.set("type1", L2Item.TYPE1_WEAPON_RING_EARRING_NECKLACE);
        item.set.set("type2", L2Item.TYPE2_WEAPON);
    }
    item.set.set("bodypart", _slots.get(rset.getString("bodypart")));
    item.set.set("material", _materials.get(rset.getString("material")));
    item.set.set("crystal_type", _crystalTypes.get(rset.getString("crystal_type")));
    item.set.set("crystallizable", Boolean.valueOf(rset.getString("crystallizable")));
    item.set.set("weight", rset.getInt("weight"));
    item.set.set("soulshots", rset.getInt("soulshots"));
    item.set.set("spiritshots", rset.getInt("spiritshots"));
    item.set.set("p_dam", rset.getInt("p_dam"));
    item.set.set("rnd_dam", rset.getInt("rnd_dam"));
    item.set.set("critical", rset.getInt("critical"));
    item.set.set("hit_modify", rset.getDouble("hit_modify"));
    item.set.set("avoid_modify", rset.getInt("avoid_modify"));
    item.set.set("shield_def", rset.getInt("shield_def"));
    item.set.set("shield_def_rate", rset.getInt("shield_def_rate"));
    item.set.set("atk_speed", rset.getInt("atk_speed"));
    item.set.set("mp_consume", rset.getInt("mp_consume"));
    item.set.set("m_dam", rset.getInt("m_dam"));
    item.set.set("duration", rset.getInt("duration"));
    item.set.set("time", rset.getInt("time"));
    item.set.set("price", rset.getInt("price"));
    item.set.set("crystal_count", rset.getInt("crystal_count"));
    item.set.set("sellable", Boolean.valueOf(rset.getString("sellable")));
    item.set.set("dropable", Boolean.valueOf(rset.getString("dropable")));
    item.set.set("destroyable", Boolean.valueOf(rset.getString("destroyable")));
    item.set.set("tradeable", Boolean.valueOf(rset.getString("tradeable")));
    item.set.set("depositable", Boolean.valueOf(rset.getString("depositable")));

    item.set.set("skills_item", rset.getString("skills_item"));
    item.set.set("enchant4_skill", rset.getString("enchant4_skill"));
    item.set.set("skills_onCast", rset.getString("skills_onCast"));
    item.set.set("skills_onCrit", rset.getString("skills_onCrit"));
    item.set.set("change_weaponId", rset.getInt("change_weaponId"));

    if (item.type == L2WeaponType.PET) {
        item.set.set("type1", L2Item.TYPE1_WEAPON_RING_EARRING_NECKLACE);
        if (item.set.getInteger("bodypart") == L2Item.SLOT_WOLF)
            item.set.set("type2", L2Item.TYPE2_PET_WOLF);
        else if (item.set.getInteger("bodypart") == L2Item.SLOT_GREATWOLF)
            item.set.set("type2", L2Item.TYPE2_PET_EVOLVEDWOLF);
        else if (item.set.getInteger("bodypart") == L2Item.SLOT_HATCHLING)
            item.set.set("type2", L2Item.TYPE2_PET_HATCHLING);
        else if (item.set.getInteger("bodypart") == L2Item.SLOT_BABYPET)
            item.set.set("type2", L2Item.TYPE2_PET_BABY);
        else
            item.set.set("type2", L2Item.TYPE2_PET_STRIDER);

        item.set.set("bodypart", L2Item.SLOT_R_HAND);
    }

    return item;
}