我有两种完全相同的方法,唯一的区别是在应用程序运行时调用其中一种方法,另一种方法是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
为什么我会收到该错误?如何解决此问题?
答案 0 :(得分:1)
如果从Java EE Web应用程序中调用常规方法connect()
,请确保您的oracle驱动程序jar位于web-inf / lib目录中