Search code examples
javaclassjdbc

what exactly does this do Class.forName("com.mysql.jdbc.Driver").newInstance();


While connecting to MySQL database I do following steps

Connection con = null;
Resultset rs = null;
Statement st = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","passwp");

Actually I wanted to know what does Class.forName("com.mysql.jdbc.Driver").newInstance(); statement do.

Althogh this class is not in mysql.jar. Where is it present?


Solution

  • Note that this answer is addresses the syntactical nature of the question, not the logical aspect. If you want a better understanding of why you would do this, see Koray Tugay's answer.

    Also note that as of Java 6, this is no longer required to initialise JDBC 4.0 drivers - instead they are automatically loaded using the service provider pattern at JVM startup.


    The Class class is located in the java.lang package, so it is distributed with java, and imported automatically into every class.

    What the forName() method does, is just return the Class object for the parameter that was loaded by the class loader. The newInstance() method then returns a new instance of the class.

    So then what happens is when you call Class.forName(...) it returns com.mysql.jdbc.Driver.class. You then call newInstance() on that class which returns an instance of the class, with no parameters, so it's basically calling new com.mysql.jdbc.Driver();.