How to implement a check for the presence of the required field in the database. If yes, then display the field on the screen. If not, it displays a message about the absence of a record.

public void searchNumber() throws SQLException { String QUERY = "select * from telephonebook.phonenumbers where name = (?) "; PreparedStatement preparedStatement = connection.prepareStatement(QUERY); System.out.print("Enter name and surname ==> "); String name = scanner.nextLine(); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getInt("id") + " " + resultSet.getString("name") + " " + resultSet.getInt("number")); } preparedStatement.close(); } 

    1 answer 1

    If the query returns an empty ResultSet, then the very first call to the next method returns false. Therefore, you can make a check before reading the results:

     ResultSet resultSet = preparedStatement.executeQuery(); if(!resultSet.next){ System.out.println("Информация отсутствует"); } 
    • I tried, everything works. The truth did not immediately want to display the available information. I redid the while construct to do while and it all worked. Thank. - Pavel Samsonenka