1. 程式人生 > >What does it mean Class.forName()

What does it mean Class.forName()

This question already has an answer here:

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");
        }
    }
}

java mysql class jdbc

165k21118178

asked Nov 7 '14 at 9:10

304

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4 Answers

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.

answered Nov 7 '14 at 9:15

165k21118178

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. :)