0

I have written the following code and the resultset (here its labelled as rs3) is returning true even though there is no result.I want to check if there is no result then the user has to enter correct phone manufacturer again.Don't know where I am going wrong?

 BufferedReader r2 = new BufferedReader(new InputStreamReader(System.in)); 
 String phone_manufacturer="";
 boolean value1=true;
 while (value1) {
    System.out.println("\nPlease select your choice of phone manufacturer " );
    String line = r2.readLine();
    if (line.matches("[A-Za-z ]+$")) {
        phone_manufacturer = line;
        final String sql3 = "SELECT * from phone_model WHERE phone_type = '"+phone_type_choice+"' and manufacturer ='"+phone_manufacturer+"'";
        st3 = connection.createStatement();
        rs3= st3.executeQuery(sql3);
        if(rs3!=null){
              System.out.println("Model"+"      "+"Manufacturer"+""+"Phone_type");
             while(rs3.next()){
                String modell  = rs3.getString("Model");
                String manufacturer = rs3.getString("Manufacturer");
                String phone_type = rs3.getString("Phone_type");
          System.out.format("%-25s%-20s%-10s\n",modell,manufacturer,phone_type);
            }
         }

         else
          {
       System.out.println("The manufacturer isn't avaiable for the phone type choosen.Please try again");
           value1=true;
           continue;
             }

     value1=false;
        }else
           {
           System.out.println("\nPlease enter correct manufacturer name " );
                            value1=true;
                            continue;

                          }
                          break;
                          }
pavikirthi
  • 1,569
  • 3
  • 17
  • 26

1 Answers1

1

Use :

if (!rs3.next() ) {
    System.out.println("no data");
}

initially the ResultSet's cursor is pointing to before the first row, if the first call to next() returns false then there was no data in the ResultSet.

if you are working with a newly returned ResultSet whose cursor is pointing before the first row, an easier way to check this is to just call isBeforeFirst().

if (!rs3.isBeforeFirst() ) {    
 System.out.println("No data"); 
} 

it's better to use prepared statment to avoid sql injection :

 PreparedStatement updateemp = connnection.prepareStatement
      ("SELECT * from phone_model WHERE phone_type =? and manufacturer=?");
      updateemp.setString(1,phone_type_choice);
      updateemp.setString(2, phone_manufacturer);

How To use prepared statement.

Ahmed Gamal
  • 1,666
  • 1
  • 17
  • 25