I'm pretty new to Java and I'm trying to get a feel for JDBC, but I'm having some issues interpreting the Java API (in particular Interfaces).
For example, Connection and Statement are interfaces, therefore a class must implement them and provide the method implementation.
Looking at below JDBC code, where is the implementation for con.createStatement() coming from?? I'm assuming that DriverManager.getConnection() is somehow providing it. Can meone assist with explaining where this method implementation comes from?? The same goes for the Statement interface, where is the method declaration for executQuery() coming from if Statement is an interface??
//Some class declaration and variable declarations
Connection con = DriverManager.getConnection(url+db, user, pass);
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee");
to find an answare to your question, I suggest you to download an Implementor of java.sql.Driver[say example: MySql] , and view the source code of *com.mysql.jdbc.Driver* . *particularly static initializer*
To connect to a database you probably read that you need a driver. In general you need a driver specific to each database. A driver comes in the form of a jar file. What you probably have not read is "What is a driver, exactly?" It is a collection of classes that implement all those interfaces!
To load a driver, you generally do something like
That generally loads a class (here "FooDriver") which implements the Driver interface. In a static initializer block, that class registers itself with the DriverManager, like
Now the DriverManager knows about the FooDriver; Driver has some methods the DriverManager can call to find out if a given Driver can connect to a given database. When the DriverManager wants a connection to the Foo database, it will ask the FooDriver class for a Connection :
But inside FooDriver, we see the implementation of connect:
and so your code ends up with a FooConnection object, but of course all you know is that it implements Connection. FooConnection doesn't even have to be a public class, and it's probably not. Then you call createStatement, and here's the code in FooConnection:
Do you see a pattern here? There's a FooResultSet, and a FooResultSetMetadata, etc. You don't need to know the names of any of those classes -- they're always returned as interface types.