我一直在寻找这个问题的答案,但还没有找到。
基本上我正在尝试通过 GUI 连接到数据库服务器。我的老板希望能够输入所有字段,然后检查它们是否是有效条目,然后如果有任何无效条目,他希望我将文本变为红色,表示该字段无效。我有 try 语句 catch ClassNotFoundException 和 SQLException。因为需要检查多个字段,所以我尝试使用一组 if 语句来检查连接信息。这是下面的代码,我希望这有意义......
//The cancel boolean values in this code are used elsewhere to regulate the Threads
try
{
//attempt connection here
}
catch(ClassNotFoundException | SQLException e)
{
String[] errors = new String[4]; //This will create a String array of the errors it catches
//and will later get called into a method that displays
//the messages in a JOptionPane.showMessageDialog()
if (e.getMessage().startsWith("The TCP/IP connection to the host"))
{
errors[0] = "SQL CONNECTION FAILED: Please check the server URL you entered to make sure it is correct.";
cancel = true;
mGUI.serverNameTextField.setForeground(Color.RED);
}
if (e.getMessage().startsWith("Login failed for user"))
{
errors[1] = "LOGIN FAILED: You do not have sufficient access to the server.";
cancel = true;
}
if (e.getMessage().startsWith("Cannot open database"))
{
errors[2] = "SQL CONNECTION FAILED: Please check the database name you entered to make sure it is correct.";
cancel = true;
mGUI.dbNameTextField.setForeground(Color.RED);
}
mGUI.reportErrors(errors); //Method where it reports the String[] array of errors
//However, the 'errors' parameter only returns one error
//message at a time, which is the problem.
谢谢你的帮助!
****编辑* ** * ** 我找到了一个解决方案,所以希望这会对某人有所帮助。我更改了我的 if 语句以添加一个 AND 参数来检查特定的错误代码。您可以通过设置断点并查看调试透视图找到错误代码,或者您可以按照我所做的并设置打印语句来查看错误代码。这是打印语句:
System.out.println(((SQLException) e).getErrorCode());
这是我的新 for 语句:
try
{
//attempt connection here
}
catch(SQLException | ClassNotFoundException e)
{
if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 0)
{
//code here
}
else{
//code here
}
System.out.println(((SQLException) e).getErrorCode()); //Here is the print statement to see the error code.
if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 4060)
{
//code here
}else{
//code here
}
if(cancel != true)
{
//code here
}
}