Here is the JAVA code that wil connect to the Oracle running on same machine as your Java code. If Oracle is installed on some other machine, you should change the IP address to point to that machine.
Code:
String url = new String();
Connection connection = null;
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.OracleDriver";
Class.forName(driverName);
// Create a connection to the database
String serverName = "127.0.0.1";
String portNumber = "1521";
String sid = "YOUR_DB_NAME";
url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "USER_NAME";
String password = "APSSWORD";
connection = DriverManager.getConnection(url, username, password);
System.err.println( "Connection To DB success");
}
catch (ClassNotFoundException e)
{
// Could not find the database driver
System.err.println( "Could not find the database driver: url: " + url +" : " + e.getMessage())
}
catch (SQLException e)
{
// Could not connect to the database
System.err.println( "Could not connect to the database");
}
You may get an error saying that "Could not find the database driver" when you run the above code from Eclipse. This is because, the code is not able to find the ojdbc14.jar for Oracle.
Add it using the following method and it will remove this error:
Right-click on project name->properties->java build path.>libraries and jar or add external jar.
It is found in following location by default:
C:\Oracle\product\11.2.0\dbhome_1\jdbc\lib\ojdbc14.jar