質問

I have a JFrame which contains a form with 3 fields, one which is the name field and one which is the house no and postcode field, this is used to find a customer details.

This works fine when the correct information is entered, and displays what I want it to inside a JTable. However if one of the fields in entered incorrectly and the information is not found, is it possible to have a custom error message to display?

At the moment the error that appears is: 'ResultSet not positioned properly, perhaps you need to call next.' is it possible to customise the message for this scenario when the information is not found without having to lose the SQL exception altogether for other scenarios where errors occur?

役に立ちましたか?

解決

I guess you are trying something like:

ResultSet rs = pstmt.executeQuery();
rs.first();
System.out.println(rs.getString("MY_COLUMN_NAME"));

You are getting this error because you are calling rs.next() or rs.first() as you said in the comments, even if there is no data in the resultset.

So instead of try following code to avoid ResultSet not positioned properly, perhaps you need to call next.' exception.

String myCustomMsg="";  //You can return this variable as custom message.
try
{
    Connection con = GET_CONNECTION_HERE;
    PreparedStatement pstmt = con.prepareStatement("QUERY HERE");
    ResultSet rs = pstmt.executeQuery();
    if(rs.next())// This will make sure that if there is no data, don't read the ResultSet
    {
        System.out.println(rs.getString("MY_COLUMN_NAME"));
        myCustomMsg = "Ok";
    }
    else
        myCustomMsg ="No Data found!";
}
catch(SQLException sqle)
{
    sqle.printStackTrace();
    myCustomMsg ="YOUR CUSTOM MESSAGE HERE....";
}

他のヒント

you can custom SQLException like this

import java.sql.SQLException;


public class SqlException extends SQLException{

    public SqlException(String message){

        super(message);
    }
    public static void main(String[] args) throws SqlException {

        throw new SqlException("name not found .!?");

    }

}  
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top