gpt4 book ai didi

java - 使用 class.ForName 注册 HSQLDB 驱动程序

转载 作者:行者123 更新时间:2023-12-01 14:50:05 25 4
gpt4 key购买 nike

我在使用 NetBeans 5.5.1 时遇到了一个奇怪的问题。我正在为我的一个类(class)创建一个测试类(class)。我正在测试的方法从名为 getConnection 的方法获取自己的连接,如下所示:

//This method was mainly done for an HSQLDB connection
public static Connection getConnection(String connectionString,String databaseDriver, String user, String pass) throws Exception
{
Connection conn = null;
try
{
System.out.println("Registering database driver "+databaseDriver);
Class.forName(databaseDriver);
System.out.println("Successfully registered database driver "+databaseDriver);
Properties props = new Properties();
props.setProperty("user",user);
props.setProperty("password",pass);

conn = DriverManager.getConnection(connectionString, props);
}
catch (ClassNotFoundException ex)
{
System.out.println("Reached catch block getConnection()");
throw new Exception ("Unable to create connection to database", ex);
}

catch (Exception ex)
{
System.out.println("Reached catch block getConnection()");
throw new Exception ("Unable to create connection to database", ex);
}

return new DatabaseConnection(conn).getConnection();

}

我使用的数据库驱动程序是HSQLDB。运行我的测试方法后,打印到输出的唯一日志语句是注册数据库驱动org.hsqldb.jdbcDriver

我的预期结果是:注册数据库驱动org.hsqldb.jdbcDriver成功注册数据库驱动org.hsqldb.jdbcDriver

当我故意使用错误的数据库驱动程序时,我可以清楚地看到抛出异常,这意味着我正在使用的上述驱动程序正在工作,并且可以在我的 classPath 中找到它。

那么问题出在哪里?

最佳答案

正如“Ian Roberts”所建议的,当将异常捕获为 Throwable 时,我意识到 Class.ForName 正在提示错误的类号(当您尝试使用比以下之一更旧的 JDK 进行编译时,会发生这种情况)你的图书馆)。将 HSQLDB 从版本 2.2.9 更改为 2.2.8.jdk5 解决了该问题。

关于java - 使用 class.ForName 注册 HSQLDB 驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14978359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com