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.nabla.wapp.report.server.ReportManager.java

protected static Integer getRole(final Connection conn, final String name) throws SQLException {
    if (name != null) {
        final PreparedStatement stmt = StatementFormat.prepare(conn,
                "SELECT id FROM role WHERE name LIKE ? AND uname IS NOT NULL;", name);
        try {//  w  w  w  . j a  v a  2  s .  c  o  m
            final ResultSet rs = stmt.executeQuery();
            try {
                if (rs.next())
                    return rs.getInt(1);
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    }
    return null;
}

From source file:com.sql.SECExceptions.java

/**
 * Gets a count of errors where the description text matches. This is to
 * eliminate the repeat of entries from the application looping
 *
 * @param description String/*from   w w  w .  ja v  a2 s. c  o  m*/
 * @return Integer count
 */
public static int getExistingException(String description) {
    int count = 0;
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT COUNT(*) AS num FROM SECExceptions WHERE "
                + "timeOccurred >= CAST(CURRENT_TIMESTAMP AS DATE) AND exceptionDescrption LIKE ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, description + "%");

        rs = ps.executeQuery();
        while (rs.next()) {
            count = rs.getInt("num");
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return count;
}

From source file:com.wso2telco.core.mnc.resolver.mncrange.McnRangeDbUtil.java

public static String getMncBrand(String mcc, String mnc) throws MobileNtException {
    Connection conn = null;//  w  ww  .  ja va2  s .  c  o m
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = "SELECT operatorname " + "FROM operators " + "WHERE mcc = ? AND mnc = ?";

    String mncBrand = null;

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        ps = conn.prepareStatement(sql);
        ps.setString(1, mcc);
        ps.setString(2, mnc);
        rs = ps.executeQuery();
        if (rs.next()) {
            mncBrand = rs.getString("operatorname");
        }
    } catch (SQLException e) {
        handleException("Error occured while getting Brand for for mcc: and mnc: " + mcc + ":" + mnc
                + " from the database", e);
    } catch (Exception e) {
        handleException("Error occured while getting Brand for for mcc: and mnc: " + mcc + ":" + mnc
                + " from the database", e);
    } finally {
        DbUtils.closeAllConnections(ps, conn, rs);
    }
    return mncBrand;
}

From source file:FacultyAdvisement.StudentRepository.java

public static Map readAll(DataSource ds) throws SQLException {
    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }//  w  ww.ja va 2 s  .c  o m

    Connection conn = ds.getConnection();

    if (conn == null) {
        throw new SQLException("conn is null; Can't get db connection");
    }

    HashMap<String, Student> list = new HashMap<>();

    try {
        PreparedStatement ps = conn.prepareStatement("select * from STUDENT");

        // retrieve customer data from database
        ResultSet result = ps.executeQuery();

        while (result.next()) {
            Student s = new Student();
            s.setId(result.getString("STUID"));
            s.setUsername(result.getString("EMAIL"));
            s.setFirstName(result.getString("FIRSTNAME"));
            s.setLastName(result.getString("LASTNAME"));
            s.setMajorCode(result.getString("MAJORCODE"));
            s.setPhoneNumber(result.getString("PHONE"));
            if (result.getString("ADVISED").equals("true")) {
                s.setAdvised(true);
            } else {
                s.setAdvised(false);
            }
            list.put(s.getId(), s);
        }

    } finally {
        conn.close();
    }

    return list;
}

From source file:com.keybox.manage.db.UserDB.java

/**
 * returns user base on id//from w  w  w.j  ava2 s  .c o m
 * @param con DB connection
 * @param userId user id
 * @return user object
 */
public static User getUser(Connection con, Long userId) {

    User user = null;
    try {
        PreparedStatement stmt = con.prepareStatement("select * from  users where id=?");
        stmt.setLong(1, userId);
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            user = new User();
            user.setId(rs.getLong("id"));
            user.setFirstNm(rs.getString(FIRST_NM));
            user.setLastNm(rs.getString(LAST_NM));
            user.setEmail(rs.getString(EMAIL));
            user.setUsername(rs.getString(USERNAME));
            user.setPassword(rs.getString(PASSWORD));
            user.setAuthType(rs.getString(AUTH_TYPE));
            user.setUserType(rs.getString(USER_TYPE));
            user.setSalt(rs.getString("salt"));
            user.setProfileList(UserProfileDB.getProfilesByUser(con, userId));
        }
        DBUtils.closeRs(rs);
        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }

    return user;
}

From source file:com.krawler.common.util.SchedulingUtilities.java

public static String getNonWorkWeekdays(Connection conn, String projid) throws ServiceException {
    String retStr = null;/*from   w  w  w . jav a2 s. com*/
    PreparedStatement pstmt = null;
    try {
        // week holidays
        pstmt = conn.prepareStatement("select day from proj_workweek where isholiday = true and projectid = ?");
        pstmt.setString(1, projid);
        ResultSet rs = pstmt.executeQuery();
        KWLJsonConverter kjs = new KWLJsonConverter();
        retStr = kjs.GetJsonForGrid(rs);
    } catch (SQLException e) {
        throw ServiceException.FAILURE("SchedulUtilities.getNonWorkWeekdays error", e);
    } finally {
        DbPool.closeStatement(pstmt);
    }
    return retStr;
}

From source file:com.silverpeas.notation.model.RatingDAO.java

private static void populateRatings(Connection con, Map<String, ContributionRating> ratings,
        String componentInstanceId, String contributionType, Collection<String> contributionIds)
        throws SQLException {
    PreparedStatement prepStmt = con.prepareStatement(
            QUERY_GET_RATINGS.replaceAll("@ids@", "'" + StringUtils.join(contributionIds, "','") + "'"));
    prepStmt.setString(1, componentInstanceId);
    prepStmt.setString(2, contributionType);
    ResultSet rs = null;/* www. j av a  2s.  com*/
    try {
        rs = prepStmt.executeQuery();
        while (rs.next()) {
            RatingRow current = resultSet2RatingRow(rs);
            ContributionRating contributionRating = ratings.get(current.getContributionId());
            if (contributionRating == null) {
                contributionRating = new ContributionRating(new ContributionRatingPK(
                        current.getContributionId(), componentInstanceId, contributionType));
                ratings.put(contributionRating.getContributionId(), contributionRating);
            }
            contributionRating.addRaterRating(current.getRaterId(), current.getRating());
        }
    } finally {
        DBUtil.close(rs, prepStmt);
    }
}

From source file:com.wso2telco.core.mnc.resolver.mncrange.McnRangeDbUtil.java

/**
 * Gets the mcc number ranges.//from  w ww.  ja va  2 s  .  c o  m
 *
 * @param mcc the mcc
 * @return the mcc number ranges
 * @throws MobileNtException the mobile nt exception
 */
public static List<NumberRange> getMccNumberRanges(String mcc) throws MobileNtException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = "SELECT mnccode,brand,rangefrom,rangeto " + "FROM mcc_number_ranges " + "WHERE mcccode = ?";

    List<NumberRange> lstranges = new ArrayList();

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        ps = conn.prepareStatement(sql);
        ps.setString(1, mcc);
        rs = ps.executeQuery();
        while (rs.next()) {
            lstranges.add(new NumberRange(rs.getLong("rangefrom"), rs.getLong("rangeto"),
                    rs.getString("mnccode"), rs.getString("brand")));
        }
    } catch (Exception e) {
        handleException("Error occured while getting Number ranges for mcc: " + mcc + " from the database", e);
    } finally {
        DbUtils.closeAllConnections(ps, conn, rs);
    }
    return lstranges;
}

From source file:com.winit.vms.base.db.mybatis.support.SQLHelp.java

/**
 * /*w  ww.  j  a v a  2s  . c  o m*/
 *
 * @param sql             SQL?
 * @param mappedStatement mapped
 * @param parameterObject ?
 * @param boundSql        boundSql
 * @param dialect         database dialect
 * @return 
 * @throws java.sql.SQLException sql
 */
public static int getCount(final String sql, final MappedStatement mappedStatement,
        final Object parameterObject, final BoundSql boundSql, Dialect dialect) throws SQLException {
    final String count_sql = dialect.getCountString(sql);
    logger.debug("Total count SQL [{}] ", count_sql);
    logger.debug("Total count Parameters: {} ", parameterObject);

    DataSource dataSource = mappedStatement.getConfiguration().getEnvironment().getDataSource();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    PreparedStatement countStmt = null;
    ResultSet rs = null;
    try {
        countStmt = connection.prepareStatement(count_sql);
        //Page SQLCount SQL???boundSql
        DefaultParameterHandler handler = new DefaultParameterHandler(mappedStatement, parameterObject,
                boundSql);
        handler.setParameters(countStmt);

        rs = countStmt.executeQuery();
        int count = 0;
        if (rs.next()) {
            count = rs.getInt(1);
        }
        logger.debug("Total count: {}", count);
        return count;
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } finally {
            try {
                if (countStmt != null) {
                    countStmt.close();
                }
            } finally {
                DataSourceUtils.releaseConnection(connection, dataSource);
            }
        }
    }
}

From source file:com.zimbra.cs.mailbox.util.MetadataDump.java

private static int getMailboxGroup(DbConnection conn, int mboxId) throws SQLException {
    int gid = 0;/* w  w w .ja v a 2 s. c o  m*/
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        stmt = conn.prepareStatement("SELECT group_id FROM mailbox WHERE id = ?");
        stmt.setInt(1, mboxId);
        rs = stmt.executeQuery();
        if (rs.next())
            gid = rs.getInt(1);
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
    }
    return gid;
}