2014-02-08 40 views
-2

我有一个JFrame,其中包含一个带有3个字段的表单,其中一个是名称字段,另一个是房屋号和邮政编码字段,用于查找客户详细信息。Java中的自定义SQL异常错误消息

当输入正确的信息时,这工作正常,并显示我想要它在JTable内。但是,如果其中一个字段输入错误且信息未找到,是否可以显示自定义错误消息?

此刻出现的错误是:'ResultSet定位不正确,或许您需要再打下一个。'是否有可能在没有找到信息的情况下自定义此场景的消息,而不必为发生错误的其他场景丢失SQL异常?

+0

定制的SQLException您能不能告诉你相关的代码? – Bhushan

+0

您可以始终使用异常链接机制来引发新异常(可能是特定于应用程序的异常),并将“SQLException”附加到该异常链接机制上。 – chrylis

+0

@Bhushan我不认为这是必要的,所有我想要的是一个异常,我可以添加到捕获(SQLException错误)显示错误信息没有找到时,代码本身工作正常,所以不需要显示它 – John

回答

2

我想你想是这样的:

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

您收到此错误,因为你在呼唤rs.next()rs.first()如您在评论中说,即使是在没有resultset数据。

因此,不要尝试下面的代码来避免ResultSet not positioned properly, perhaps you need to call next.'异常。

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

谢谢,你明白我想要的东西,而不用把代码放好,好的! – John

+0

@John不用客气。 – Bhushan

1

你可以这样

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 .!?"); 

    } 

}