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.
Use the Class. forName() method to load the driver. The forName() method dynamically loads a Java class at runtime. When an application calls the forName() method, the Java Virtual Machine (JVM) attempts to find the compiled form (the bytecode) that implements the requested class.
The forName() method of Java Class class returns the Class object associated with the class or interface with the given name in the parameter as String.
forName() method may throw an exception at the time of returning a Class object. LinkageError: This exception may throw when we get linking error. ExceptionInInitializeError: In this exception when the initialization is done by this method fails.
The forName() method of java. lang. Class class is used to get the instance of this Class with the specified class name. This class name is specified as the string parameter.
Class.forName
simply loads a class, including running its static initializers, like this:
class Foo { static { System.out.println("Foo initializing"); } } public class Test { public static void main(String [] args) throws Exception { Class.forName("Foo"); } }
All the rest of the procedure you're talking about is JDBC-specific. The driver - which implements Driver
, it doesn't extend DriverManager
- simply registers an appropriate instance using DriverManager.registerDriver
. Then when DriverManager
needs to find a driver for a particular connection string, it calls connect
on 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 DriverManager
for more modern ways of getting at a data source.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With