Example usage for java.sql PreparedStatement executeQuery

List of usage examples for java.sql PreparedStatement executeQuery

Introduction

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

Prototype

ResultSet executeQuery() throws SQLException;

Source Link

Document

Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

Usage

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

private HennaTreeTable() {
    int classId = 0;
    int count = 0;
    Connection con = null;/*from   w  w  w .ja v a 2s.c o  m*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement("SELECT id FROM class_list");
        ResultSet classlist = statement.executeQuery();

        while (classlist.next()) {
            classId = classlist.getInt("id");
            FastList<L2Henna> list = new FastList<L2Henna>();

            PreparedStatement statement2 = con
                    .prepareStatement("SELECT symbol_id FROM henna_trees where class_id=?");
            statement2.setInt(1, classId);
            ResultSet hennatree = statement2.executeQuery();

            while (hennatree.next()) {
                int id = hennatree.getInt("symbol_id");

                L2Henna template = HennaTable.getInstance().getTemplate(id);
                if (template == null) {
                    hennatree.close();
                    statement2.close();
                    classlist.close();
                    statement.close();
                    return;
                }

                list.add(template);
            }
            hennatree.close();
            statement2.close();

            count += list.size();
            _hennaTrees.put(classId, list.toArray(new L2Henna[list.size()]));
        }

        classlist.close();
        statement.close();
        _log.info("HennaTreeTable: Loaded " + count + " Henna Tree Templates.");
    } catch (Exception e) {
        _log.warn("Error while creating henna tree for classId " + classId + " ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

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

private void load() {
    FastMap<Integer, FastList<L2Skill>> tempMap = new FastMap<Integer, FastList<L2Skill>>();
    Connection con = null;//  w  w w . ja  v a2s . c om

    int skills = 0;
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement = con.prepareStatement("SELECT * FROM skill_residential ORDER BY entityId");
        ResultSet rs = statement.executeQuery();

        while (rs.next()) {
            int entityId = rs.getInt("entityId");
            int skillId = rs.getInt("skillId");
            int skillLvl = rs.getInt("skillLevel");

            L2Skill sk = SkillTable.getInstance().getInfo(skillId, skillLvl);

            if (sk == null) {
                _log.warn("ResidentialSkillTable: SkillTable has returned null for ID/level: " + skillId + "/"
                        + skillLvl);
                continue;
            }
            if (!tempMap.containsKey(entityId)) {
                FastList<L2Skill> aux = new FastList<L2Skill>();
                aux.add(sk);
                tempMap.put(entityId, aux);
            } else
                tempMap.get(entityId).add(sk);
            ++skills;
        }
        statement.close();
        rs.close();

        for (Map.Entry<Integer, FastList<L2Skill>> e : tempMap.entrySet()) {
            _list.put(e.getKey(), e.getValue().toArray(new L2Skill[e.getValue().size()]));
        }
    } catch (Exception e) {
        _log.error("ResidentialSkillTable: a problem occured while loading skills!", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
    _log.info("ResidentialSkillTable: Loaded " + _list.size() + " entities with " + skills
            + " associated skills.");
}

From source file:dao.MaterialDaoImplem.java

@Override
public Material selectMaterial(int id_material) {
    try (Connection connection = dataSource.getConnection()) {
        String query = ("select * from material m WHERE m.id_material=?");
        PreparedStatement stat = connection.prepareStatement(query);
        stat.setInt(1, id_material);/*from   w  w  w  . j av a2 s.c  om*/
        ResultSet res = stat.executeQuery();
        if (res.next()) {
            Material material = new Material();
            material.setId_material(res.getInt(1));
            material.setName(res.getString(2));
            material.setWeight(res.getInt(3));
            material.setManufacturer(res.getString(4));
            material.setCost(res.getInt(5));
            material.setQuantity(res.getInt(6));
            return material;
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new RuntimeException("Error:selectMaterial", e);
    }
}

From source file:com.nabla.wapp.server.xml.Importer.java

public <T> T read(final Class<T> clazz, final Integer dataId, final String userSessionId)
        throws DispatchException, SQLException {
    final PreparedStatement stmt = StatementFormat.prepare(conn, sql, dataId);
    try {/*from   www.j av a  2  s. c om*/
        final ResultSet rs = stmt.executeQuery();
        try {
            if (!rs.next()) {
                errors.add(CommonServerErrors.NO_DATA);
                return null;
            }
            if (!userSessionId.equals(rs.getString("userSessionId"))) {
                if (log.isTraceEnabled())
                    log.trace("invalid user session ID");
                errors.add(CommonServerErrors.ACCESS_DENIED);
                return null;
            }
            try {
                return impl.read(clazz, rs.getBinaryStream("content"));
            } catch (final InvocationTargetException e) {
                if (log.isDebugEnabled())
                    log.debug("exception thrown from a validate(). assume error was added to list", e);
            } catch (final ValueRequiredException e) {
                if (log.isDebugEnabled())
                    log.debug("required value", e);
                errors.add(Util.extractLine(e), Util.extractFieldName(e), CommonServerErrors.REQUIRED_VALUE);
            } catch (final ElementException e) {
                errors.add(Util.extractFieldName(e), e.getLocalizedMessage());
            } catch (final PersistenceException e) {
                if (log.isDebugEnabled())
                    log.debug("deserialization error", e);
                errors.add(Util.extractLine(e), Util.extractFieldName(e), CommonServerErrors.INVALID_VALUE);
            } catch (final XMLStreamException e) {
                if (log.isDebugEnabled())
                    log.debug("XML error", e);
                errors.add(Util.extractLine(e), e.getLocalizedMessage());
            } catch (final Exception e) {
                if (log.isDebugEnabled())
                    log.debug("error", e);
                errors.add(Util.extractLine(e), e.getLocalizedMessage());
            }
            return null;
        } finally {
            Database.close(rs);
        }
    } finally {
        Database.close(stmt);
    }
}

From source file:io.kamax.mxisd.backend.wordpress.WordpressThreePidProvider.java

protected Optional<_MatrixID> find(ThreePid tpid) {
    String query = cfg.getSql().getQuery().getThreepid().get(tpid.getMedium());
    if (Objects.isNull(query)) {
        return Optional.empty();
    }//from   w  w w . j  a v  a  2  s . c  o m

    try (Connection conn = wordpress.getConnection()) {
        PreparedStatement stmt = conn.prepareStatement(query);
        stmt.setString(1, tpid.getAddress());

        try (ResultSet rSet = stmt.executeQuery()) {
            while (rSet.next()) {
                String uid = rSet.getString("uid");
                log.info("Found match: {}", uid);
                try {
                    return Optional.of(MatrixID.from(uid, mxCfg.getDomain()).valid());
                } catch (IllegalArgumentException ex) {
                    log.warn("Ignoring match {} - Invalid characters for a Matrix ID", uid);
                }
            }

            log.info("No valid match found in Wordpress");
            return Optional.empty();
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.mayo.bmi.dictionary.jdbc.JdbcDictionaryImpl.java

public boolean contains(String text) throws DictionaryException {
    try {//from  w w  w.  j ava2 s .c  om
        PreparedStatement prepStmt = initCountPrepStmt(text);
        ResultSet rs = prepStmt.executeQuery();

        rs.next();
        int count = rs.getInt(1);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    } catch (SQLException e) {
        throw new DictionaryException(e);
    }
}

From source file:com.rajaram.bookmark.dao.BookmarkDaoImpl.java

@Override
public List<Bookmark> getBookmarks(String userName) {

    String sql = "select * from " + tableName + " where user_name = ?";

    Connection conn = null;//from   w w  w  .jav a2s  .c om
    BookmarkRowMapper rowExtract = new BookmarkRowMapper();
    List<Bookmark> bookmarks = null;

    try {
        conn = dataSource.getConnection();
        PreparedStatement prepareStatement = conn.prepareStatement(sql);
        prepareStatement.setString(1, userName);
        ResultSet rs = prepareStatement.executeQuery();

        bookmarks = rowExtract.mapRow(rs);

        rs.close();
        prepareStatement.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }

    return bookmarks;
}

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

private void load() {
    Connection con = null;/*from w w  w.j a  v a  2s. c o m*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();

        PreparedStatement statement = con
                .prepareStatement("SELECT maxplayer, date FROM record ORDER BY maxplayer DESC LIMIT 1");
        ResultSet rset = statement.executeQuery();

        if (rset.next()) {
            _record = rset.getInt("maxplayer");
            _date = rset.getString("date");
        }

        rset.close();
        statement.close();
    } catch (Exception e) {
        _log.warn("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.mirth.connect.server.controllers.tests.TestUtils.java

public static int getNumMessages(String channelId, boolean onlyCountMessagesWithContent) throws Exception {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet result = null;//from  w  w w.ja va  2 s .c o  m

    try {
        long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId);

        StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM d_m" + localChannelId + " m");

        if (onlyCountMessagesWithContent) {
            query.append(" WHERE EXISTS (SELECT 1 FROM d_mc" + localChannelId + " WHERE message_id = m.id)");
        }

        connection = getConnection();
        statement = connection.prepareStatement(query.toString());
        result = statement.executeQuery();
        result.next();
        return result.getInt(1);
    } finally {
        close(result);
        close(statement);
        close(connection);
    }
}

From source file:com.senior.g40.service.UserService.java

private long getLatestUserId() throws SQLException {
    Connection conn = ConnectionBuilder.getConnection();
    String sqlCmd = "SELECT MAX(userId) AS latestId FROM `profile`;";
    PreparedStatement pstm = conn.prepareStatement(sqlCmd);
    ResultSet rs = pstm.executeQuery();
    if (rs.next()) {
        long latestId = rs.getLong("latestId");
        conn.close();/*from  ww w  .j a v  a 2 s  . c o  m*/
        return latestId;
    } else {
        conn.close();
        throw new SQLException("Latest userId is N/A.");
    }
}