Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'Class.forName("org.sqlite.JDBC");' do?

Tags:

java

sqlite

jdbc

People also ask

What is SQLite JDBC?

The SQLite JDBC driver allows you to load an SQLite database from the file system using the following connection string: jdbc:sqlite:sqlite_database_file_path. Code language: Java (java)

Why do we use class forName?

forName(String name, boolean initialize, ClassLoader loader) method returns the Class object associated with the class or interface with the given string name, using the given class loader. The specified class loader is used to load the class or interface.

What does class forName do in JDBC?

Use the Class. forName() method to load the driver. The forName() method dynamically loads a Java class at runtime. When an application calls the forName() method, the Java Virtual Machine (JVM) attempts to find the compiled form (the bytecode) that implements the requested class.

Why do we use class forName com mysql JDBC driver?

It will create a new instance of the com. mysql. jdbc. Driver class and hence call the static initialization which will register the driver with the DriverManager so you can create mysql connections based on the URL you use in the second line.


It loads a class dynamically. What does Class.forname method do? is a good article about it and it also explains why database drivers needs it:

Let's see why you need Class.forName() to load a driver into memory. All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static an initializer only.

The MySQL JDBC Driver has a static initializer looks like this:

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

JVM executes the static block and the Driver registers itself with the DriverManager.

You need a database connection to manipulate the database. In order to create the connection to the database, the DriverManager class has to know which database driver you want to use. It does that by iterating over the array (internally a Vector) of drivers that have registered with it and calls the acceptsURL(url) method on each driver in the array, effectively asking the driver to tell it whether or not it can handle the JDBC URL.


The Class.forName statement is making sure that the class that implements the JDBC driver for sqlite3 is loaded and registered with the JDBC factory mechanism.

When you call DriverManager.getConnection(), it looks for classes that are registered and claim to be able to handle the connection string. If no such class is found, it can't create the connection.