Java does not give Error!
Here is my code - I am just checking the MySQL database connection.
But first I compiled and ran the program successfully. but then I commented out the Class.forName line.
However, when I compile it, it succeeds without any errors. 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();
}
}
}
source to share
Java 1.6 can find the JDBC driver even without using Class.forName.
Here's an important piece of documentation :
The methods
DriverManager
getConnection
andgetDrivers
have been extended to support the Java Standard Edition service provider mechanism. JDBC 4.0 drivers must include aMETA-INF/services/java.sql.Driver
. This file contains the name of the JDBC driver implementationjava.sql.Driver
. For example, to load a classmy.sql.Driver
, the fileMETA-INF/services/java.sql.Driver
will contain the entry:
my.sql.Driver
Applications no longer need to explicitly load JDBC drivers using Class.forName (). Existing programs that currently load JDBC drivers using Class.forName () will continue to work unchanged.
source to share
NOTE. This only applies to the pre-JDBC 4.0 drivers.
JDBC drivers must have a section static
that registers them with java.sql.DriverManager
when the class is loaded, so it is required Class.forName(String)
.
Details here: http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/drivermanager.html
source to share
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 a statement inside the catch block, then compile and run, you will see an error message like -
[Some Com] [Some Driver Manager] Data source name not found and specified default driver not specified
source to share