This section describes what will happen if incorrect database names specified in the connection URL.
If you selected a wrong database, or the login name has no access to that database,
getConnection() method will throw a SQLExection object for you to catch. In this case,
the getMessage() method of the SQLExection object will give you the detailed error message.
The tutorial program below shows you an example of the SQLException resulting from a wrong database name
in the connection URL:
/**
* WrongDatabase.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class WrongDatabase {
public static void main(String [] args) {
Connection con = null;
try {
// Load Microsoft JDBC Driver 1.0
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Obtaining a connection to SQL Server
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1269;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLI");
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: "
+e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: "
+e.getMessage());
}
}
}
You will get the following message, if you run it:
C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar
WrongDatabase
SQLException: Cannot open database "AdventureWorksLI" requested
by the login. The login failed.
The error message is not so accurate. The login was correct.
The select database operation was failed, because database "AdventureWorksLI"
does not exist on the SQL Server.