Reputation: 2446
Here is my code - i am simply checking my MySQL database connection.
But first i have compiled and run the program successfully. but then i have commented the line Class.forName .
Still when i compile it runs successfully, without any error.Why?
import java.sql.Connection;
import java.sql.DriverManager;
public class FirstJbdc {
public static void main(String[] args) {
Connection cn=null;
try {
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded successfully");
cn=DriverManager.getConnection("jdbc:odbc:myDSN","root", "java");
System.out.println("Database connected successfully....");
System.out.println(cn);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Upvotes: 2
Views: 347
Reputation: 34321
NOTE: this only applies to pre-JDBC 4.0 Drivers.
JDBC drivers are meant to have a static
section that registers them with the java.sql.DriverManager
when the class is loaded, hence the Class.forName(String)
is required.
It's detailed here: http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/drivermanager.html
Upvotes: 1
Reputation: 75496
Without Class.forName()
, the JDBC-ODBC bridge driver is not loaded. By JDBC specification, getConnection()
returns null if no driver is found for the URL, no exception is thrown. So this is expected behavior.
Upvotes: 0
Reputation: 32901
Java 1.6 can find JDBC driver even without using Class.forName.
Here is relevant part of documentation:
The
DriverManager
methodsgetConnection
andgetDrivers
have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the fileMETA-INF/services/java.sql.Driver
. This file contains the name of the JDBC drivers implementation ofjava.sql.Driver
. For example, to load themy.sql.Driver
class, theMETA-INF/services/java.sql.Driver
file would contain the entry:my.sql.Driver
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
Upvotes: 7
Reputation: 18712
try {
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded successfully");
cn=DriverManager.getConnection("jdbc:odbc:myDSN","root", "java");
System.out.println("Database connected successfully....");
System.out.println(cn);
} catch (Exception e) {
// add the following statement
System.out.println(e.getMessage());
}
If you add the statement inside the catch block, then compile and run, you should see the error message like-
[Some Com][Some Driver Manager] Data source name not found and no default driver specified
Upvotes: 0
Reputation: 6849
I throws an error, alright. It's just that the
catch (Exception e){
// here the exception is instantiated, but nothing is done about it
}
clause silently swallows your exception.
Try a
System.out.println( e.getMessage() );
in the catch clause
Upvotes: 8