为什么 H2 不需要 JDBC 驱动程序
Why is JDBC driver not necessary for H2
我有一个非常简单的 Java 使用 H2 内存数据库的入门应用程序:
String DB_URL = "jdbc:h2:./test";
try(Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmnt = conn.createStatement() ){
// executing SQLs, getting a result set, etc.
...
}
// Catching & handling exceptions
该应用程序可以运行,但是,我想知道为什么我不必在我的代码中的任何地方调用 Class.forName(JDBC_DRIVER);
?在所有 H2 快速启动中,他们手动加载 class。
您不需要为未满岁的任何 JDBC driver 执行此操作。由于 Java、as documented 的服务提供商机制,驱动程序 auto-discovered:
The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:
my.sql.Driver
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
请注意,与您的问题标题相反,JDBC driver 是必需的。使用 Class.forName() 加载它是不必要的。
我有一个非常简单的 Java 使用 H2 内存数据库的入门应用程序:
String DB_URL = "jdbc:h2:./test";
try(Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmnt = conn.createStatement() ){
// executing SQLs, getting a result set, etc.
...
}
// Catching & handling exceptions
该应用程序可以运行,但是,我想知道为什么我不必在我的代码中的任何地方调用 Class.forName(JDBC_DRIVER);
?在所有 H2 快速启动中,他们手动加载 class。
您不需要为未满岁的任何 JDBC driver 执行此操作。由于 Java、as documented 的服务提供商机制,驱动程序 auto-discovered:
The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:
my.sql.Driver
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
请注意,与您的问题标题相反,JDBC driver 是必需的。使用 Class.forName() 加载它是不必要的。