Can't connect to oracle database using jdbc thin drivers
I am trying to connect to Oracle Database 10 XE using Oracle thin drivers, but I cannot get it. I even added drivers to my classpath at compile time.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class Connectivity {
public static void main(String args[]) throws SQLException {
String url = "jdbc:oracle:thin:@localhost:1521:XE";
Properties props = new Properties();
props.setProperty("user", "SYSTEM");
props.setProperty("password", "iiita");
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
Connection conn = DriverManager.getConnection(url,props);
String sql ="select sysdate as current_day from dual";
PreparedStatement preStatement = conn.prepareStatement(sql);
ResultSet result = preStatement.executeQuery();
while(result.next()){
System.out.println("Current Date from Oracle : " + result.getString("current_day"));
}
System.out.println("done");
}
}
This code gives the following error when run
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@localhost:1521/XE
at java.sql.DriverManager.getConnection(DriverManager.java:644)
at java.sql.DriverManager.getConnection(DriverManager.java:202)
at Connectivity.main(Connectivity.java:16)
source to share
You forgot to specify the ojdbc14 classpath when starting the main class:
For Windows: java -cp .;<path>/ojdbc14.jar Connectivity
On Linux: java -cp .:<path>/ojdbc14.jar Connectivity
PS You don't need ojdbc14.jar for your class to compile the main class. This is a runtime dependency.
source to share
Add this line before calling getConnection(url, props)
Class.forName ("oracle.jdbc.driver.OracleDriver");
It is not enough to have jars on the classpath unless they are jdbc> 4.0 drivers. You must register the driver with DriverManager
.
Change jdbc:oracle:thin:@localhost:1521:XE
to jdbc:oracle:thin:@//localhost:1521:XE
. I believe this is new syntax.
Compile as
javac -classpath /<your_path>/ojdbc6.jar Connectivity.java
Running from
java Connectivity
source to share