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:fp4f.floorplans.DatabaseLayer.java

HouseItem getHouse(AddressItem selected) {
    HouseItem house = new HouseItem();
    try {//from  w  w w  .ja v a  2 s  .c o  m
        PreparedStatement getter = con.prepareStatement("select * from houses where id = ?");
        getter.setInt(1, selected.HouseId);
        ResultSet rs = getter.executeQuery();

        house.Id = rs.getInt("id");

        house.Address = rs.getString("address");
        house.Phone = rs.getString("phone");

        house.Adults = rs.getInt("adults");
        house.Children = rs.getInt("children");
        house.Elderly = rs.getInt("elderly");
        house.Pets = rs.getInt("pets");
        house.Salvage = rs.getInt("salvage");
        house.Complexity = rs.getInt("complexity");

        house.Weapons = rs.getBoolean("weapons");

        house.Disabilities = rs.getString("disability");
        house.Combustables = rs.getString("combustables");
        house.Community = rs.getString("community");

        house.Floors = getFloors(house.Id);
    } catch (Exception ex) {
        System.out.println(ex);
    }
    return house;
}

From source file:adept.kbapi.sql.QuickJDBC.java

/**
 * execute query to check if object exists in the database. This closes the
 * prepared statement passed in/*from   w ww .  j  ava 2  s . co m*/
 */
public boolean recordExists(PreparedStatement preparedStmt) throws SQLException {
    boolean doesRecordExist = false;
    java.sql.ResultSet rs = null;
    try {
        rs = preparedStmt.executeQuery();
        doesRecordExist = rs.next();
    } finally {
        try {
            if (rs != null)
                rs.close();
        } catch (Exception e) {
        }
        ;
        try {
            if (preparedStmt != null)
                preparedStmt.close();
        } catch (Exception e) {
        }
        ;
    }
    return doesRecordExist;
}

From source file:JoinGameServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Enumeration paramNames = request.getParameterNames();
    String params[] = new String[3];
    int i = 0;/*from  w w  w.  j a  va2  s  .co  m*/
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        //System.out.println("ParamName : " +paramName);

        String[] paramValues = request.getParameterValues(paramName);
        params[i] = paramValues[0];
        //System.out.println("ParamValue : " +params[i]);

        i++;
    }
    //System.out.println("param0->"+params[0]);
    //System.out.println("param1->"+params[1]);
    //param0->gameid,param1->name

    DatabaseHandler db = new DatabaseHandler();

    conn = db.makeConnection();

    String query = "SELECT * FROM game WHERE id=" + params[0];
    //System.out.println(query);

    PreparedStatement prStmt;
    try {
        prStmt = conn.prepareStatement(query);
        ResultSet rs = prStmt.executeQuery();

        if (rs.next()) {
            String count = rs.getString("playercount");
            count = String.valueOf(Integer.parseInt(count) + 1);

            String qry = "UPDATE game SET nameplayer" + count + "=\"" + params[1] + "\",playercount=\"" + count
                    + "\" WHERE id=\"" + params[0] + "\"";
            //System.out.println(qry);

            stmt = conn.createStatement();
            int updatedRows = stmt.executeUpdate(qry);
            if (updatedRows == 1) {
                json.put("reply", "done");
                json.put("actionid", count);
                //setting next player action to 1 to start bet
                if (Integer.parseInt(count) == 4) {
                    qry = "UPDATE game SET turn=1,nextactionuserid=1 WHERE id=\"" + params[0] + "\"";
                    stmt.execute(qry);
                }
            } else {
                json.put("reply", "undone");
            }
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json.toString());

    } catch (SQLException ex) {
        Logger.getLogger(JoinGameServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    db.closeAllConnections(conn, stmt);

}

From source file:com.smartmarmot.common.db.DBJob.java

private boolean Alive(Connection _conn) {
    try {//from w  w  w.  ja  v a  2  s  .c o  m
        PreparedStatement p_stmt = null;
        p_stmt = _conn.prepareStatement(Constants.ORACLE_VALIDATION_QUERY);
        ResultSet rs = null;
        rs = p_stmt.executeQuery();
        rs.next();
        //_conn.close();
        return true;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        SmartLogger.logThis(Level.DEBUG, "Database " + this._dbname + " is not alive");
        return false;
    }
}

From source file:iddb.web.security.dao.SessionDAO.java

public Session get(String key) throws EntityDoesNotExistsException {
    String sql = "select * from user_session where id = ?";
    Connection conn = null;/*  ww  w . j av  a 2s. c o m*/
    Session session = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setString(1, key);
        ResultSet rs = st.executeQuery();
        if (rs.next()) {
            session = new Session();
            loadSession(session, rs);
        } else {
            throw new EntityDoesNotExistsException("Session with key %s was not found", key);
        }
    } catch (SQLException e) {
        log.error("get", e);
    } catch (IOException e) {
        log.error("get", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return session;
}

From source file:org.apache.kylin.jdbc.KylinConnectionTest.java

@Test
public void testPrepareStatementWithMockKylinClient() throws SQLException, IOException {
    String sql = "select 1 as val";
    // mock client
    when(client.executeQuery(anyString(), Mockito.<List<Object>>any(), Mockito.<Map<String, String>>any()))
            .thenReturn(getMockResult());

    try (KylinConnection conn = getConnectionWithMockClient()) {
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        try (ResultSet resultSet = preparedStatement.executeQuery()) {
            verify(client).executeQuery(eq(sql), Mockito.<List<Object>>any(),
                    Mockito.<Map<String, String>>any());

            assertTrue(resultSet.next());
            ResultSetMetaData metaData = resultSet.getMetaData();
            assertEquals("VAL", metaData.getColumnName(1));
            assertEquals(1, resultSet.getInt("VAL"));
        }/*from   w  ww .j  a  v a 2  s .co m*/
    }
}

From source file:com.Assignment4.Prod.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *///  w w  w  . j a  v a2s.c  o  m
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() throws SQLException {
    if (connect == null) {
        return "not connected";
    } else {
        String query = "Select * from product";
        PreparedStatement preparedst = connect.prepareStatement(query);
        ResultSet rs = preparedst.executeQuery();
        String result = "";
        JSONArray productArr = new JSONArray();
        while (rs.next()) {
            Map pMap = new LinkedHashMap();
            pMap.put("productID", rs.getInt("product_id"));
            pMap.put("name", rs.getString("name"));
            pMap.put("description", rs.getString("description"));
            pMap.put("quantity", rs.getInt("quantity"));
            productArr.add(pMap);
        }
        result = productArr.toString();
        return result.replace("},", "},\n");
    }

}

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

@Override
public List<KeyWords> getkeyWordList(int images_images_id) {
    List<KeyWords> list = new ArrayList<KeyWords>();
    try {//  w  w  w. ja v  a 2s . com
        String sql = "SELECT * FROM key_words WHERE images_images_id=?";
        Connection con = DBFactory.getConnection();
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1, images_images_id);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            KeyWords kw = new KeyWords();
            kw.setImages_images_id(rs.getInt(3));
            kw.setKey_word(rs.getString(2));
            kw.setKey_words_id(rs.getInt(1));
            list.add(kw);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}

From source file:com.oracle.products.ProductResource.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *//*from ww w.  j a  v  a2s.  c om*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() throws SQLException {
    if (conn == null) {
        return "not connected";
    } else {
        String query = "Select * from product";
        PreparedStatement pstmt = conn.prepareStatement(query);
        ResultSet rs = pstmt.executeQuery();
        String result = "";
        JSONArray productArr = new JSONArray();
        while (rs.next()) {
            Map productMap = new LinkedHashMap();
            productMap.put("productID", rs.getInt("product_id"));
            productMap.put("name", rs.getString("name"));
            productMap.put("description", rs.getString("description"));
            productMap.put("quantity", rs.getInt("quantity"));
            productArr.add(productMap);
        }
        result = productArr.toString();
        return result.replace("},", "},\n");
    }

}

From source file:mercury.DigitalMediaDAO.java

public final DigitalMediaDTO getDigitalMedia(int id, String fileName) {
    Connection con = null;//www.ja  v  a 2  s  .  c  om
    byte[] blob = null;
    DigitalMediaDTO dto = new DigitalMediaDTO();
    try {
        con = getDataSource().getConnection();
        String sql = " SELECT file, file_name, mime_type FROM digital_media " + " WHERE id = ? "
                + " AND file_name = ? ;";
        PreparedStatement pst = con.prepareStatement(sql);
        pst.setInt(1, id);
        pst.setString(2, fileName);
        con.setAutoCommit(false);
        ResultSet rs = pst.executeQuery();
        if (rs.next()) {
            blob = rs.getBytes(1);
            if (blob == null) {
                return null;
            }
            dto.setIn(new ByteArrayInputStream(blob));
            dto.setLength((int) blob.length);
            dto.setFileName(rs.getString(2));
            dto.setMimeType(rs.getString(3));
        }
        return dto;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(con);
    }
}