'jdbc DriverManager.getConnection("connection_url", "username", "password");

Can anyone tell me wats happening here

Connection con =DriverManager.getConnection("connection_url", "username", "password");

How connection interface and driverManager class are related ? I mean con is a connection interface reference which can point to an object of a class which implements connection interface or an object/instance which is related to connection interface .....what "DriverManager.getConnection" is returning and how it can be referred by a connection reference ??

I know the basic answer dat it returns a connection by checking the url of the driver but what is actually happening in detail ?

I am a beginner java student please help



Solution 1:[1]

The DriverManager keeps track of all JDBC Drivers that have been loaded in your JVM (there are a couple of ways in which a Driver can be loaded).

When you ask the DriverManager to open a connection for you, it asks each of the loaded drivers whether it can handle the URL that you've specified.
If the Driver can handle the URL, then it is asked to connect to the database using the supplied username and password. The Driver supplies a connection object that implements the Connection interface.

The DriverManager really is just a small class that knows about each loaded Driver and handles picking the right one. The implementation of Connection (and Statement, etc) is all handled by the Driver.

Solution 2:[2]

I mean con is a connection interface reference which can't point to an object of a class which implements connection interface

Wrong. It can and it must. The actual implementation class is provided by the JDBC driver vendor.

Solution 3:[3]

See, here DriverManager.getConnection("connection_url", "username", "password"); is not the obj of java.sql.Connection(interface). It's the obj of JDBC driver Class that implements Connection (I). please note that Interface can't be instantiated (i. object can't be created) but it can hold / refer to obj of implementation class (i.e Driver class and driver class changes based on database we want connect to).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim
Solution 2 user207421
Solution 3 Suraj Rao