2016-05-05 5 views
0

結果がないのに結果セット(ここではrs3というラベルが付いています)が返されています。結果がない場合は、ユーザーが入力する必要があります正しい電話機製造業者。どこが間違っているのか分かりませんか?jdbcのresultsetがtrueを返しています

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; 
          } 
+0

あなたがすべきではSystem.out場合(!resultSet.isBeforeFirst()){ そのようにチェックします。 println( "データなし"); } –

+2

executeQuery **常に**は空であっても結果セットを返します。 –

+0

rs3.next()がtrueを返すと言っていますか?ところで、あなたのコードはSQLインジェクションに脆弱ですので、ほんの一例です。 IE。、誰かがphone_type = "1; DROP TABLE phone_model; - " – Jamie

答えて

1

使用:(次の最初の呼び出し場合

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

最初ResultSetのカーソルは、最初の行の前を指している)をResultSet内のデータがなかったfalseを返します。

カーソルが最初の行の前を指している新しく返されたResultSetを操作している場合、これをチェックする簡単な方法はisBeforeFirst()を呼び出すことです。

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

これは、SQLインジェクションを防ぐために、プリペアドステートメントを使用することをお勧めします:

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.

関連する問題