I just learned about java.sql package. It uses Class.forName() to dynamically load the driver which extends DriverManager.
Then we get connection using DriverManager.getConnection() method.
So how does the entire thing work?
How does DriverManager class know how to get the connection without using class name of the actual driver.
Also can we use Class.forName() for custom applications… if this is explained with an example I will be very happy.
Class.forNamesimply loads a class, including running its static initializers, like this:All the rest of the procedure you’re talking about is JDBC-specific. The driver – which implements
Driver, it doesn’t extendDriverManager– simply registers an appropriate instance usingDriverManager.registerDriver. Then whenDriverManagerneeds to find a driver for a particular connection string, it callsconnecton each registered driver in turn until one succeeds and returns a non-null connection.Note that this way of registering drivers is reasonably old-fashioned – look at the docs for
DriverManagerfor more modern ways of getting at a data source.