1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] How to check if entered value is equal to a value in a SQL database?

Discussão em 'Outras Linguagens' iniciado por Stack, Novembro 7, 2024 às 17:12.

  1. Stack

    Stack Membro Participativo

    I have a database with 7 rows, and 4 columns in each. I am prompting an user to enter a code, and I need to cross reference the database to see if the entered code equals one of the codes in the database (first column in each row).

    At first, I was checking if the result set came up as null, but that was not working. I was trying if(rs.wasNull()), but it never seemed to execute.

    Does anybody have any advice on what to look at to solve my issue? Here's a code snippet if helps at all.

    if(!rs.wasNull()) {
    while(rs.next()) {
    Products temp = new Products(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBoolean(4));
    productsList.add(temp);
    // For testing purposes
    //out.println(temp.toString());
    request.setAttribute("productsList", productsList);
    request.getRequestDispatcher("Scan.jsp").forward(request, response);
    }
    }

    else if(rs.wasNull()) {
    Products wrongCode = null;
    productsList.add(wrongCode);
    request.setAttribute("productsList", productsList);
    request.getRequestDispatcher("Scan.jsp").forward(request, response);
    }


    EDIT: I now know that ResultSet never returns null. It will return an empty ResultSet.

    EDIT 2: I've wrote this method to solve the problem:

    public boolean codeExists(int code) {
    final String SELECT_QUERY = "SELECT * FROM productcatalogue WHERE code = ?";
    try {

    PreparedStatement statement = conn.prepareStatement(SELECT_QUERY); // Create query statement
    statement.setInt(1, code);

    ResultSet queryResult = statement.executeQuery();
    if (!queryResult.next()) { // Check if code entered exists
    return false; // Tells that the author doesn't exist
    }
    } catch (SQLException sqlException) {

    sqlException.printStackTrace();

    }
    return true; //Otherwise the item exists
    }

    Continue reading...

Compartilhe esta Página