3

I was learning JDBC, only thing i don't get is class Class in following code.

Whether I delete Class.forName("com.mysql.jdbc.Driver") or not, it works properly.

Could you explain what function is Class.forName("com.mysql.jdbc.Driver") in this part?

import java.sql.*;
public class JSP {

    public static void main(String[] args){
        Connection myConn = null;
        Statement st= null;
        ResultSet rs= null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/customer", "root", "Gspot");

            st = myConn.createStatement();
            String query = "select * from customers";

            rs = st.executeQuery(query);
            while(rs.next()){
                System.out.println(rs.getString("name"));
            }
        } catch(SQLException e){
            e.printStackTrace();
        } catch(ClassNotFoundException e) {
            System.out.println("wow");
        }
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
user4067001
  • 65
  • 1
  • 5

4 Answers4

9

Class.forName creates an instance of a java.lang.Class corresponding to the given name. This forces the classloader to load this class, and execute any code in its static blocks.

Older JDBC drivers used to use these static block to register themselves to the java.sql.DriverManager so they can later be used to connect to the database. JDBC 4, which was part of Java 6, introduced a mechanism to automatically load JDBC drivers, so this is no longer needed.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
5

Class.forName("com.mysql.jdbc.Driver") would get the class object for the named class via reflection.

If that class exists there's no difference between having that line in the code or not, you're not doing anything with the return value. However, if it doesn't exist on the classpath you'd get an exception from that call and thus you'd know that the driver is missing instead of the connection just failing.

Assume the MySQL driver is not present on the classpath.

Without that statement, you might an error like "could not open connection" and it might be up to you to parse the logs and look for the reason why.

If the statement is called, you'd get a ClassNotFoundException and thus you'd know the reason for the problems: the driver classes are not found by the classloader.

Edit: reading @Mureinik's answer, that's probably the better reason for that statement. :)

Thomas
  • 87,414
  • 12
  • 119
  • 157
2

I recommend you to read this paper: Understanding-ClassforName-Java

If you are calling Class.forName("com.mysql.jdbc.Driver"); the driver class com.mysql.jdbc.Driver will be loaded into memory. Every such Driver classes have static block like this:

static {
    try {
         java.sql.DriverManager.registerDriver(new Driver());
     } catch (SQLException E) {
         throw new RuntimeException("Can't register driver!");
     }
}

So if you're loading the class, the static block will be called automatically an driver will be (if success) registered.

alex
  • 8,904
  • 6
  • 49
  • 75
1

According to the documentation (http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)) :

A call to forName("X") causes the class named X to be initialized.

which means that the class is loaded from the disk, and its static initializers are called, such as:

public class Test {
    private static final int a;    
    static { // called when the class is loaded via forName or any other loading mechanism
        a = 5;
        doSomething(a);
    }
    private static int doSomething(int x) {
        return (x+5);
    }
}

This only happens once, when the class is loaded. For example in your case, we can suppose that it allows the driver to run code to register itself into JDBC.

If omitting this call for you doesn't alter runtime behaviour, it means that the class has already been loaded before.

SirDarius
  • 41,440
  • 8
  • 86
  • 100