Reputation: 9819
I have two methods that are exactly the same, the only difference is that one of them is called while the app is running, and the other is a main(String[] args)
method.
The main method works, although that only posts console information.
The other method, however, is supposed to return the connection object. Instead, I get a ClassNotFoundException
.
Working code:
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");
}
}
result:
-------- Oracle JDBC Connection Testing ------
Oracle JDBC Driver Registered!
Happy
However if I call it as a regular method instead of in my main
method, I get the error. This is the code:
Error code:
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");
}
}
result:
-------- Oracle JDBC Connection Testing ------
Where is your Oracle JDBC Driver?
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
Why do I get that error and how do I solve this problem?
Upvotes: 2
Views: 275
Reputation: 535
if the regular method connect()
is called from within say a Java EE web application, make sure your oracle driver jars are in the web-inf/lib directory
Upvotes: 1