What does Class.forName () mean

I have been learning JDBC, only I am not getting the class class in the following code.

Whether I delete Class.forName("com.mysql.jdbc.Driver")

or not, it works correctly.

Could you please explain what is the Class.forName ("com.mysql.jdbc.Driver") function 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");
        }
    }
}

      

+3


source to share


4 answers


Class.forName

creates an instance java.lang.Class

corresponding to the given name. This forces the class loader to load this class and execute any code in its blocks static

.



Older JDBC drivers used this static block to register for java.sql.DriverManager

so they could 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.

+9


source


Class.forName("com.mysql.jdbc.Driver")

will get the class object for the named class via reflection.

If this class exists, there is no difference whether this string is in the code or not, you do nothing with the return value. However, if it does not exist on the classpath, you will get an exception from that call, and hence you will know that the driver is missing, not just a connection failure.

Let's assume the MySQL driver is missing in the classpath.



Without this statement, an error may occur, such as "connection cannot be opened", and you may need to analyze the logs and look for the cause.

If a statement is called, you will get, ClassNotFoundException

and therefore you will know, the cause of the problem: the driver classes were not found by the class loader.

Edit: reading @ Mureinik's answer, which is probably the best reason for this statement. :)

+4


source


I recommend you read this article: Understanding-ClassforName-Java

If you call Class.forName("com.mysql.jdbc.Driver");

, the com.mysql.jdbc.Driver driver class will be loaded into memory . Each such driver class has a 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 load the class, the static block will be called automatically when the driver is registered (if successful).

+1


source


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

Calling forName ("X") initializes the class named X.

which means the class is loaded from disk and its static initializers are called like:

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 might assume that it allows the driver to run the code to register with JDBC.

If the exception of this call does not change the behavior at runtime for you, it means that the class has already been loaded before.

0


source







All Articles