【发布时间】:2017-02-14 04:05:30
【问题描述】:
我有两个完全一样的方法,唯一的区别是其中一个是在应用运行时调用的,另一个是main(String[] args)方法。
main 方法有效,尽管它只发布控制台信息。
然而,另一种方法应该返回连接对象。相反,我得到一个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 目录中。 -
@AkioHamasaki 是的,它是一个网络应用程序,我明天将尝试该解决方案,我已按常规方式添加了 jar。如果您愿意,可以将其作为答案。
-
@Randy 我将其添加为答案。有机会时告诉我们进展情况。
-
这与您的问题无关,但请注意
oracle.jdbc.driver.OracleDriver已经过时了很长时间,您现在应该使用oracle.jdbc.OracleDriver
标签: java oracle jakarta-ee jdbc