Where is the java.sql.Connection interface implemented?

I am using interface connection from java.sql package

Actually I, although this is a class, but when I tried to look at the source code, I realized that it was an interface.

In the source of the Connection interface, there is only one line for each method without any implementation!

How does this interface work?

Database to connect to: MySql

Connection source code page: http://www.docjar.com/html/api/java/sql/Connection.java.html

+4
source share
3 answers

This is not an interface that "works", but one of its implementations that is specific to your specific RDBMS provider. In fact, typically the provider provides an implementation of the Connection interface.

When you call

 Connection conn = DriverManager.getConnection( "jdbc:jdbc:mysql://localhost:3306/ , connectionProps); 

The driver manager looks through registered JDBC drivers, finds it for MySQL (it knows its MySQL from the connection string), passes the connection properties to the class constructor inside the MySQL JDBC driver, which implements Connection and returns the result. Connection return to you. For example, a driver can return an instance of the private-private MySqlConnection that implements Connection , and your program will use it to interact with the RDBMS without any class information, except that it implements Connection .

+9
source

The MySQL driver ( http://www.mysql.com/products/connector/ ) contains the actual implementation. The java.sql.Connection interface simply defines the methods that the JDBC standard expects. Each database driver must determine how to actually connect.

+2
source

Here are a few examples of classes that directly or indirectly implement the java.sql.Connection interface:

  • oracle.jdbc. OracleConnectionWrapper
  • com.mysql.jdbc. ConnectionImpl
  • com.microsoft. sqlserver.jdbc. SQLServerConnection

In the package namespace, you can specify which jdbc driver they are from. But these and other implementation classes should not be used directly. As pointed out by dasblinkenlight, you should program against the JDBC API, not the classes provided in each JDBC driver library. Using the API will allow you to switch RDBMS and not break your java data access code.

Interestingly, fewer and fewer people today use the JDBC API. Many people use an object-relational mapping structure that is built on top of JDBC, such as Hibernate.

+1
source

All Articles