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

前端 未结 2 1550
离开以前
离开以前 2020-12-03 10:35

I am trying to create a simple app with a SQLite database. I chose to use the SQLiteJDBC driver.

The code below is taken from the above website. My question is abou

相关标签:
2条回答
  • 2020-12-03 10:47

    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.

    0 讨论(0)
  • 2020-12-03 10:47

    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.

    0 讨论(0)
提交回复
热议问题