Welcome Guest! To enable all features please Register.

Notification

Icon
Error

New Topic Post Reply
How to create JDBC connection with Oracle in Java Code
Guest
#1 Posted : Friday, October 07, 2011 3:03:55 AM(UTC)
Rank: Guest

Joined: 12/12/2009(UTC)
Posts: 443
Points: 1,361
I need to connect to Oracle from Java code. Can anybody help me with the code?
Sponsor

Soan
#2 Posted : Friday, October 07, 2011 3:13:03 AM(UTC)
Rank: Administration
Soan

Joined: 1/9/2010(UTC)
Posts: 393
Points: 1,158
Location: India
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
Quick Reply Show Quick Reply
Users browsing this topic
Guest
New Topic Post Reply
Forum Jump  
You can post new topics in this forum.
You can reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.