java.sql.SQLException: No suitable driver found
To be clear, this exception can have two causes:
- The driver is not loaded.
- The (wrong) URL didn t return
true
for Driver#acceptsURL()
for any of the loaded drivers.
Now back to your "workaround" which is actually the solution:
Note that this seems more like a workaround than a true solution because why would this be required in a web app and not in a non-web app?
JDBC4 has a new feature: the DriverManager
will auto-load any drivers which are in the classpath and definied in service loaders of JAR files. This will only work in Java6 environments. Maybe your problem is that the webserver is using a Java5 JVM.
I would however not always rely on it and just stick with using Class#forName()
. In a well designed DAO layer you need to do this only once. Or, even better, just let the webcontainer manage a datasource for it so that you can take benefit from connection pooling and thus a major improvement in connecting performance.
Further on I would clear out one misconception:
Class.forName("full.driver.name").newInstance()
The newInstance()
call is actually not required for properly designed JDBC drivers. A decent JDBC driver will register itself as follows:
static {
DriverManager.registerDriver(new ThisDriver());
}
But poorly designed JDBC drivers (of which there should actually be none nowadays, this has only occurred in one of the oldest versions of the MySQL JDBC driver if I am correct) did the following:
private ThisDriver() {
DriverManager.registerDriver(this);
}
which thus really needed the newInstance()
call to get itself registered. This became a myth because everyone was since then recommended to do so. That s not needed. Just leave it away and you ll save an unnecessary instantiation.
Hope this helps.