gpt4 book ai didi

java - 仅当不在主方法中时才出错 : oracle. jdbc.driver.OracleDriver ClassNotFoundException

转载 作者:行者123 更新时间:2023-11-30 10:38:05 26 4
gpt4 key购买 nike

我有两个完全相同的方法,唯一的区别是其中一个是在应用程序运行时调用的,另一个是 main(String[] args) 方法。

主要方法有效,尽管它只发布控制台信息。

然而,另一种方法应该返回连接对象。相反,我得到了一个 ClassNotFoundException

工作代码:

public static void main(String[] args) throws ClassNotFoundException, SQLException {

System.out.println("-------- Oracle JDBC Connection Testing ------");

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

} catch (ClassNotFoundException e) {

System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();

throw e;
}

System.out.println("Oracle JDBC Driver Registered!");

try {

connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "randy",
"test");

} catch (SQLException e) {

System.out.println("Connection Failed! Check output console");
e.printStackTrace();
throw e;

}

if (connection != null) {
System.out.println("Happy");
} else {
throw new SQLException("Failed to setup the connection");
}
}

结果:

-------- Oracle JDBC Connection Testing ------
Oracle JDBC Driver Registered!
Happy

但是,如果我将其作为常规方法而不是在我的 main 方法中调用,则会出现错误。这是代码:

错误代码:

public static Connection connect() throws SQLException, ClassNotFoundException {

if(connection != null){
return connection;
}

System.out.println("-------- Oracle JDBC Connection Testing ------");

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

} catch (ClassNotFoundException e) {

System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
throw e;
}

System.out.println("Oracle JDBC Driver Registered!");

try {

connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "randy",
"test");

} catch (SQLException e) {

System.out.println("Connection Failed! Check output console");
e.printStackTrace();
throw e;

}

if (connection != null) {
return connection;
} else {
throw new SQLException("Failed to setup the connection");
}
}

结果:

-------- Oracle JDBC Connection Testing ------
Where is your Oracle JDBC Driver?
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

为什么会出现该错误以及如何解决该问题?

最佳答案

如果常规方法 connect() 是从 Java EE web 应用程序中调用的,请确保您的 oracle 驱动程序 jar 位于 web-inf/lib 目录中

关于java - 仅当不在主方法中时才出错 : oracle. jdbc.driver.OracleDriver ClassNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39878573/

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