我编写了以下代码,结果集(此处标记为rs3)返回true,即使没有结果。我想检查是否没有结果,然后用户必须再次输入正确的手机制造商.Don&不知道我哪里出错了吗?
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 :(得分:1)
使用:
if (!rs3.next() ) {
System.out.println("no data");
}
最初ResultSet的游标指向第一行之前,如果第一次调用next()返回false,那么ResultSet中没有数据。
如果您正在使用新返回的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);