Saturday 6 October 2012

how to connect java to oracle database

Connect Java to Oracle Database


package com.action.dbConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnectionProvider {
      String serverName = "119.45.2.23";
      String sid = "xyz";     // String sid given by Oracle
      String username = "uid";
      String password = "pwd";
      String driverName = "oracle.jdbc.driver.OracleDriver";
      String portNumber = "2008";
      Connection connection = null;
     
      public Connection connect() {
            try {
System.out.println("Inside class DbConnectionProvider, Method connect()");
                  // Load the JDBC driver
                   Class.forName(driverName);
                  // Create a connection to the database
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
connection = DriverManager.getConnection(url, username, password);
            } catch (ClassNotFoundException e) {
                // Could not find the database driver
                  System.out.println("Could not find the database driver");
                  e.printStackTrace();
            } catch (SQLException e) {
                // Could not connect to the database
                  System.out.println("Could not connect to the database");
            } finally {
                 
            }
            return connection;
      }

No comments:

Post a Comment