Reputation: 344
I am wondering how JDBC knows which database driver class it should use.
Example:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection verbindung = DriverManager.getConnection("jdbc:derby:d:/memory/onlineshop;create=true");
The first line takes Care, that a driver (EmbeddedDriver) will be loaded into to class loader (and so be available, e.g. for using with reflections, right?).
So, the next line is my connection string. It starts with:
jdbc:derby:...
I expected something like this instead:
jdbc:ConcreteDriverClassForInit
As you can see i am missing a link between the class loaded in the class loader and the connection string call of that class.
I searched in the derby archive for a class named "Derby.Class" - but there is no such class.
Even when I try sth. like this, JDBC still knows, what to do:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Class.forName("org.something.anyotherDBDriver1");
Class.forName("org.something.anyotherDBDriver2");
Connection verbindung = DriverManager.getConnection("jdbc:derby:d:/memory/onlineshop;create=true");
But why? Thanks for your help!
Upvotes: 3
Views: 2493
Reputation: 121712
In previous versions of JDBC, to obtain a connection, you first need to load your JDBC driver by calling the method Class.forName().
Currently any JDBC 4.0 drivers that are found in your class path are automatically loaded. So, there is not even the need for Class.forName()
.
The gist of it is to be found in the documentation for java.sql.Driver
and java.sql.DriverManager
.
Basically, starting with JDBC 4, all you have to do is create a META-INF/services/java.sql.Driver
file for your SQL driver implementation and the JRE will load it automatically. Which means that you can directly try and do:
DriverManager.getConnection("yourUrlHere")
If one driver recognizes the URL, it will be used automatically.
Upvotes: 1
Reputation: 19811
That EmbeddedDriver
class has a static block executed when you load the class that adds an handler for the specific JDBC type:
static {
EmbeddedDriver.boot();
}
Check the code of the boot method here, and you'll see where the protocol is registered:
new JDBCBoot().boot(Attribute.PROTOCOL, ps);
That specific string is located in org.apache.derby.iapi.reference
:
String PROTOCOL = "jdbc:derby:";
That's a common pattern that is followed by all JDBC drivers, i don't particularly like the code of this driver, if you want a cleaner example look at the SQLite driver, way more straightforward implementation:
static {
try {
DriverManager.registerDriver(new JDBC());
}
catch (SQLException e) {
e.printStackTrace();
}
}
org.sqlite.JDBC
will register itself to the java.sql.DriverManager
that will invoke JDBC.isValidURL(String url)
to know if this class is a valid driver for a specific JDBC url
, the SQLite driver will return true
only if the url
contains the PREFIX
jdbc:sqlite:
.
Upvotes: 5