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:ca.phon.ipadictionary.impl.DatabaseDictionary.java

private void checkLangId(Connection conn) throws SQLException {
    final String checkSQL = "SELECT * FROM language WHERE langId = ?";
    final PreparedStatement checkSt = conn.prepareStatement(checkSQL);
    checkSt.setString(1, getLanguage().toString());
    final ResultSet checkRs = checkSt.executeQuery();

    if (!checkRs.next()) {
        final String insertSQL = "INSERT INTO language (langId) VALUES ( ? )";
        final PreparedStatement insertSt = conn.prepareStatement(insertSQL);
        insertSt.setString(1, getLanguage().toString());
        insertSt.execute();/*w  w  w . j  av a 2 s  . c  o  m*/
        insertSt.close();
    }
    checkSt.close();
}

From source file:cai.sql.SQL.java

public ResultSet exec(String msg, PreparedStatement stm) throws DoneException {
    ResultSet re = null;/* w  w  w  .j  a  va  2  s. c o  m*/

    try {
        re = stm.executeQuery();
    } catch (SQLException e) {
        error_msg(msg, e, null);
    }

    return re;
}

From source file:com.ywang.alone.handler.task.AuthTask.java

/**
 * ? { 'key':'2597aa1d37d432a', 'pNo':'0' }
 * // ww  w .  j  a  va2 s.  c  om
 * @param param
 * @return
 */
private static String getAllFollows(String msg) {
    JSONObject jsonObject = AloneUtil.newRetJsonObject();
    JSONObject param = JSON.parseObject(msg);
    String token = param.getString("key");
    String userId = null;

    if (StringUtils.isEmpty(token)) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
    } else {
        Jedis jedis = JedisUtil.getJedis();
        Long tokenTtl = jedis.ttl("TOKEN:" + token);
        if (tokenTtl == -1) {
            jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
            jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
            jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);

        } else {
            userId = jedis.get("TOKEN:" + token);
            if (StringUtils.isEmpty(userId)) {
                jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
                jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
                jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);

            }
        }
        JedisUtil.returnJedis(jedis);
    }

    if (StringUtils.isEmpty(userId)) {
        return jsonObject.toJSONString();
    }

    LoggerUtil.logMsg("uid is " + userId);

    DruidPooledConnection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = DataSourceFactory.getInstance().getConn();
        conn.setAutoCommit(false);

        stmt = conn.prepareStatement(
                "SELECT * FROM USERBASE WHERE USER_ID IN (SELECT FOLLOWED_ID FROM FOLLOW WHERE USER_ID = ?)");
        stmt.setString(1, userId);

        ArrayList<UserInfo> followedList = new ArrayList<UserInfo>();
        UserInfo userInfo = null;
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {

            userInfo = new UserInfo();
            userInfo.setUserId(rs.getString("USER_ID"));
            userInfo.setAvatar(rs.getString("AVATAR"));
            userInfo.setNickName(rs.getString("NICKNAME"));
            userInfo.setAge(rs.getString("AGE"));
            userInfo.setRoleName(rs.getString("ROLENAME"));
            userInfo.setOnline(rs.getString("ONLINE"));
            userInfo.setLastLoginTime(rs.getLong("LAST_LOGIN_TIME"));
            userInfo.setIntro(rs.getString("INTRO"));
            userInfo.setDistance(rs.getString("DISTANCE"));

            followedList.add(userInfo);
        }

        conn.commit();
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        LoggerUtil.logServerErr(e);
        jsonObject.put("ret", Constant.RET.SYS_ERR);
        jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR);
        jsonObject.put("errDesc", Constant.ErrorDesc.SYS_ERR);
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
            if (null != conn) {
                conn.close();
            }
        } catch (SQLException e) {
            LoggerUtil.logServerErr(e.getMessage());
        }
    }

    return jsonObject.toJSONString();
}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * This method is important for the GUI to generate the necessary rows
 * before the options with the values of the database will be added.
 * //ww w. j  a  v a  2  s  . co  m
 * @return the number of rows, which are saved in the database.
 */
public static synchronized int getControllerSize() {
    int size = 0;
    createDBConnection();
    try {
        Statement st = conn.createStatement();
        PreparedStatement stp = conn.prepareStatement("select count(*) from \"Controller\" ;");
        ResultSet r = stp.executeQuery();
        r.next();
        size = r.getInt(1);

    } catch (SQLException e) {
        logger.error("SQL Exception", e);
    }
    closeDBConnection();

    return size;
}

From source file:dhbw.clippinggorilla.objects.user.UserUtils.java

/**
 * Checks whether email already exists in database
 *
 * @param email The email to be checked//from w  w w.  j a v a  2 s . c o m
 * @return true if mail exists
 */
public static boolean checkEmailExisting(String email) {
    try {
        String sql = "SELECT * FROM " + Tables.USER + " WHERE " + Columns.EMAIL + " = ?";
        PreparedStatement stat = Database.getConnection().prepareStatement(sql);
        stat.setString(1, email);
        return stat.executeQuery().next();
    } catch (SQLException ex) {
        Log.warning("SQL failed on check whether user exists", ex);
        return false;
    }
}

From source file:fp4f.floorplans.DatabaseLayer.java

ArrayList<FloorItem> getFloors(int houseId) {
    ArrayList<FloorItem> floors = new ArrayList<FloorItem>();
    try {//w ww .  jav a2 s. c o m
        PreparedStatement getter = con
                .prepareStatement("select * from floors where house = ? order by level desc");
        getter.setInt(1, houseId);
        ResultSet rs = getter.executeQuery();

        while (rs.next()) {
            FloorItem floor = new FloorItem();
            floor.Id = rs.getInt("id");
            floor.HouseId = houseId;
            floor.Level = rs.getInt("level");
            floor.FloorPlan = rs.getString("image");
            floor.load();

            floors.add(floor);
        }

    } catch (Exception ex) {
        System.out.println(ex);
    }

    return floors;
}

From source file:com.fpmislata.banco.persistencia.impl.MovimientoBancarioDAOImplJDBC.java

@Override
public MovimientoBancario get(int id) {
    MovimientoBancario movimientoBancario = new MovimientoBancario();
    Connection connection = connectionFactory.getConnection();
    String SQL = "SELECT * FROM movimientobancario WHERE id = ? ";
    try {//w ww. ja  v a  2s.  co m
        PreparedStatement preparedStatement = connection.prepareStatement(SQL);
        preparedStatement.setInt(1, id);
        ResultSet resultSet = preparedStatement.executeQuery();
        resultSet.next();
        movimientoBancario.setId(resultSet.getInt("id"));
        movimientoBancario.setCuentaPertenece(resultSet.getInt("cuentapertenece"));
        movimientoBancario.setImporte(resultSet.getString("importe"));
        movimientoBancario.setFecha(resultSet.getDate("fecha"));
        movimientoBancario.setSaldoTotal(resultSet.getString("saldototal"));
        movimientoBancario.setTipoMovimiento(resultSet.getString("tipomovimiento"));
        movimientoBancario.setConcepto(resultSet.getString("concepto"));

        return movimientoBancario;
    } catch (Exception ex) {
        throw new RuntimeException("Error al hacer la consulta", ex);
    } finally {
        try {
            connection.close();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

}

From source file:com.uit.anonymousidentity.Repository.Nonces.NonceJDBCTemplate.java

@Override
public boolean isFresh(Nonce n) throws SQLException {
    String sql = "select * from " + TABLE_NAME + " where " + SID + " = ? and " + VALUE + " = ?";
    PreparedStatement pst = dataSource.getConnection().prepareStatement(sql);
    pst.setString(1, n.getIssuerSid());//  w  ww .ja v a 2 s  .c om
    pst.setBytes(2, n.getByteArray());

    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        return false;
    } else
        return true;

}

From source file:com.mobilewallet.users.dao.BalanceDAO.java

public Balance balanceInfo(long userId) {
    Balance w = null;/*  www . ja va 2  s  .c o  m*/
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = dataSource.getConnection();
        pstmt = con.prepareStatement(walletInfoQuery);
        pstmt.setLong(1, userId);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            w = new Balance();
            w.setAmount(rs.getFloat("w_amount"));
            w.setTotalAmount(rs.getFloat("w_total_credits"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (con != null) {
                con.close();
            }
        } catch (Exception ex) {

        }
    }
    return w;
}

From source file:com.webbfontaine.valuewebb.action.rimm.RefSelect.java

public static String getDataForGcnet(String findWhat, String from, String key, String keyValue) {
    Connection connection = Utils.getSQLConnection();
    ResultSet rs = null;//  w  w  w. j  a  v a2s .c  o m
    PreparedStatement preparedStatement = null;
    try {
        String sql = "select " + findWhat + " from " + from + " where " + key + " = ?";
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, keyValue);
        rs = preparedStatement.executeQuery();
        if (rs.next()) {
            return rs.getString(findWhat);
        }
    } catch (SQLException e) {
        LOGGER.error(e, "");
    } finally {
        DBUtils.closeResources(rs, preparedStatement, connection);
    }

    return null;
}