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.fpmislata.banco.persistencia.impl.MovimientoBancarioDAOImplJDBC.java

@Override
public List<MovimientoBancario> findAll() {
    List<MovimientoBancario> movimientosBancarios = new ArrayList<>();
    Connection connection = connectionFactory.getConnection();
    String SQL = "SELECT * FROM movimientobancario ";

    try {//from   w ww  . j av a 2s.  c om
        PreparedStatement preparedStatement = connection.prepareStatement(SQL);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            MovimientoBancario movimientoBancario = new MovimientoBancario();
            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"));
            movimientosBancarios.add(movimientoBancario);
        }

        return movimientosBancarios;
    } 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.imagelake.control.KeyWordsDAOImp.java

@Override
public List<KeyWords> listKeyWords(String key) {
    List<KeyWords> lis = new ArrayList<KeyWords>();

    try {/*from w  w w.  j  a  va 2  s. c o  m*/
        String sql = "SELECT * FROM key_words WHERE key_word LIKE '%" + key
                + "%' ORDER BY images_images_id DESC";
        PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql);

        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            System.gc();
            KeyWords w = new KeyWords();
            w.setKey_words_id(rs.getInt(1));
            w.setKey_word(rs.getString(2));
            w.setImages_images_id(rs.getInt(3));
            System.out.println("image id:" + rs.getInt(3));
            lis.add(w);
        }
    } catch (Exception e) {
        e.printStackTrace();

    }
    return lis;
}

From source file:com.l2jfree.gameserver.communitybbs.Manager.UpdateBBSManager.java

private List<UpdateItem> getChangeLog() {
    List<UpdateItem> _items = new FastList<UpdateItem>();
    java.sql.Connection con = null;
    try {//from   w  w  w  .  j a  v a 2s .  com
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement("SELECT * FROM changelog order by id desc");
        ResultSet result = statement.executeQuery();
        while (result.next()) {
            UpdateItem it = new UpdateItem();
            it.id = result.getInt("id");
            it.udate = result.getString("udate");
            it.introduction = result.getString("introduction");
            it.text = result.getString("text");
            it.author = result.getString("author");
            _items.add(it);
        }
        result.close();
        statement.close();
    } catch (Exception e) {
        _log.warn("couldnt load changelog", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
    return _items;
}

From source file:MyPack.AjaxAlbumList.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request// w ww  .  java  2 s .  c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");
    HttpSession s = request.getSession(true);
    try (PrintWriter out = response.getWriter()) {
        //getting AJAX parameter
        String query = request.getParameter("term");
        //Creating JSONArray Object
        JSONArray arrayObj = new JSONArray();
        //Changing Case of AJAX parameter
        query = query.toLowerCase();
        try {
            Connection con = ConnectionClass.getConnected();
            PreparedStatement p = con
                    .prepareStatement("select albumName from album where albumName LIKE '" + query + "%'");
            ResultSet rs = p.executeQuery();
            while (rs.next() == true) {
                arrayObj.put(rs.getString(1));
            }
            out.println(arrayObj.toString());
            out.close();
        } catch (SQLException ea) {
        }
    }
}

From source file:com.imagelake.control.KeyWordsDAOImp.java

@Override
public String getAllKeyWords() {
    StringBuffer sb = null;/* w  ww  . j a v  a 2s . co  m*/
    try {
        sb = new StringBuffer("{'keywords':{");
        sb.append("'words':[");

        String sql = "SELECT * FROM key_words GROUP BY key_word";
        PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            if (rs.isLast()) {
                sb.append("{'id':'" + rs.getInt(1) + "','keyword':'" + rs.getString(2) + "','imgid':'"
                        + rs.getInt(3) + "'}");
            } else {
                sb.append("{'id':'" + rs.getInt(1) + "','keyword':'" + rs.getString(2) + "','imgid':'"
                        + rs.getInt(3) + "'},");
            }
        }
        sb.append("]");
        sb.append("}");
        sb.append("}");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

/**
 * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by
 * {@link PreparedStatement}./*from ww  w . j ava2  s .com*/
 * 
 * @param session the session
 * @param queryString the query
 * @param parameters parameters to substitute in the query
 * @return the results of the query as an Object[] (an array cell per column)
 */
public static List<Object[]> runSql(Session session, final String queryString, final Object[] parameters) {
    final List<Object[]> result = new ArrayList<Object[]>();

    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(queryString);
                ResultSet rs = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        stmt.setObject(i + 1, parameters[i]);
                    }
                    rs = stmt.executeQuery();
                    ResultSetMetaData md = rs.getMetaData();
                    int cc = md.getColumnCount();
                    while (rs.next()) {
                        Object[] current = new Object[cc];
                        for (int i = 0; i < cc; i++) {
                            current[i] = rs.getObject(i + 1);
                        }
                        result.add(current);
                    }
                } finally {
                    if (null != rs) {
                        rs.close();
                    }
                    if (null != stmt) {
                        stmt.close();
                    }
                }
            }
        });
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }

    return result;
}

From source file:com.mycompany.rubricatelefonica.DefaultSmartphoneDao.java

public SmartphoneModel getSmartphoneInfo(String imei) {

    SmartphoneModel smartphoneModel = new SmartphoneModel();

    MysqlDataSource dataSource = new MysqlDataSource();

    dataSource.setUser("root");
    dataSource.setPassword("root");
    dataSource.setUrl("jdbc:mysql://localhost:3306/RubricaTelef");

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

    try {

        conn = dataSource.getConnection();

        PreparedStatement stmtUserInfo = conn.prepareStatement(SMARTPHONE_INFO);

        stmtUserInfo.setString(1, imei);

        ResultSet rsUserInfoSet = stmtUserInfo.executeQuery();

        if (rsUserInfoSet.first()) {

            smartphoneModel = new SmartphoneModel();
            smartphoneModel.setMarca(rsUserInfoSet.getString("marca"));
            smartphoneModel.setModello(rsUserInfoSet.getString("modello"));
            smartphoneModel.setColore(rsUserInfoSet.getString("colore"));
            smartphoneModel.setMateriale(rsUserInfoSet.getString("materiale"));

        }

    } catch (SQLException e) {
        System.out.println(e.getMessage());
        System.out.println("errore!!");
    } finally {

        DbUtils.closeQuietly(conn); //oppure try with resource
    }

    return smartphoneModel;
}

From source file:net.sf.l2j.gameserver.model.entity.ClanHallSiege.java

public long restoreSiegeDate(int ClanHallId) {
    long res = 0;
    Connection con = null;/*from w  w  w .  j a  v a 2 s  . c  o  m*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement = con.prepareStatement("SELECT siege_data FROM clanhall_siege WHERE id=?");
        statement.setInt(1, ClanHallId);
        ResultSet rs = statement.executeQuery();
        if (rs.next())
            res = rs.getLong("siege_data");
        rs.close();
        statement.close();
    } catch (Exception e) {
        _log.error("Exception: can't get clanhall siege date: " + e.getMessage(), e);
    } finally {
        try {
            if (con != null)
                con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return res;
}

From source file:controladores.controladorEmpleados.java

@Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
    String apellido = hsr.getParameter("txtApellido");
    ModelAndView mv = new ModelAndView("index");
    Connection con = getConexion();
    ResultSet rs = null;//  w  ww .  j a  va 2s .  c o  m
    if (apellido == null) {
        Statement stmt = con.createStatement();
        rs = stmt.executeQuery("Select apellido, oficio, salario, nvl(comision,0) comision from emp");
    } else {
        PreparedStatement ps = con.prepareStatement(
                "Select apellido, oficio, salario, nvl(comision,0) comision from emp where apellido = ?");
        ps.setString(1, apellido);
        rs = ps.executeQuery();
    }
    ArrayList al = new ArrayList();
    while (rs.next()) {
        Empleado emp = new Empleado();
        emp.setApellido(rs.getString("apellido"));
        emp.setOficio(rs.getString("oficio"));
        emp.setSalario(rs.getInt("salario"));
        emp.setComision(rs.getInt("comision"));
        al.add(emp);
    }
    mv.addObject("lista", al);
    return mv;
}

From source file:FlavorListServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");

    // Get the bounds of the ranks to be listed
    // or use defaults

    int lowLimit = getLimit(request.getParameter("lowLimit"), 0);
    int highLimit = getLimit(request.getParameter("highLimit"), 100);

    Connection con = null;/* ww w . j  a  v  a2s  .c om*/
    try {

        // Connect to the ice cream database

        Class.forName(JDBC_DRIVER);
        con = DriverManager.getConnection(URL);

        // Run a query to get the top flavors

        String sql = "SELECT  RANK, NAME" + "   FROM flavors" + "   WHERE RANK BETWEEN ? AND ?"
                + "   ORDER BY RANK";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setInt(1, lowLimit);
        pstmt.setInt(2, highLimit);
        ResultSet rs = pstmt.executeQuery();

        // Print as an ordered list

        out.println("<ol>");
        while (rs.next()) {
            int rank = rs.getInt(1);
            String name = rs.getString(2);
            out.println("   <li>" + name + "</li>");
        }
        out.println("</ol>");
    } catch (SQLException e) {
        throw new ServletException(e.getMessage());
    } catch (ClassNotFoundException e) {
        throw new ServletException(e.getMessage());
    }

    // Close the database

    finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ignore) {
            }
        }
    }
}