检查搜索元素是否在数据库中不可用

to check whether the search element isn't available in DB

我正在使用 phpmy admin,我需要显示 "Not Found" 消息以防在数据库中找不到搜索元素。 使用的代码在这里。

Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
 ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");

我用这个方法搜索 empId,如果 empId 在数据库中不可用,我需要显示一个 message.Please 如果 empId 在数据库中不可用,请给我一个如何检测的解决方案。

像这样使用 if 语句

Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
     do
     {
         // If there is data, then process it
     }
     while(rs.next());
}
else
    System.out.println("Not Found");

将文本解析添加到整数,假设 empId 是一个整数。

int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
    String sql = "SELECT *" +
                  " FROM nonacademic" +
                 " WHERE empId = ?";
    try (Statement s = c.prepareStatement(sql)) {
        s.setInt(1, empId);
        try (ResultSet rs = s.executeQuery()) {
            if (! rs.next()) {
                // not found
            } else {
                // found, call rs.getXxx(...) to get values
            }
        }
    }
}
 if (rs != null)
{
  out.println("result set has got something");
  while (rs.next())
  { 
    //I am processing result set now
  }
}
else
{
  out.println("Not Found");
}

只需使用基本的简单 if & else 语句。如果 ResultSet 是 "null" 或者它不包含任何记录,则显示消息,否则读取数据并显示。

Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
         // record found do the processing
else
    System.out.println("Not Found"); 
  String e = txtempId.getText();
  String sql="select *from nonacademic where empId='"+ e+"' ";
   try {
    boolean status=DatabaseConnection.checkValue(sql);
     if (status) {
         JOptionPane.showMessageDialog(null,
          "This id is available");    

          } else {

          JOptionPane.showMessageDialog(null,
          "Not found");
                      }
         } catch (Exception e) {
    }

此方法return检查搜索元素是否存在

   public static boolean checkValue(String sql) throws Exception {
    boolean b = false;
    ResultSet rst = null;
    Statement st = getStatement();
    rst = st.executeQuery(sql);
    if (rst.next()) {
        b = true;
    }
    return b;
}