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

前端 未结 2 1552
离开以前
离开以前 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.

提交回复
热议问题