Tuesday, 17 January 2017

ESTABLISH CONNECTION TO DATABASE


  • DriverManager provide the following method - static Connection getConnection(String url, String user, String password)
  • Attempt to establish a connection to the given database URL
  • getConnection method of DriverManager uses registered driver in-order to establish connection to database.
  • Establishing connection is nothing but creating a session.
URL : Uniform Resource Locator


DriverManager.getConnection(String url, String uname, String pwd);

1. Protocol : Driver specific protocol used by DriverManager for selecting JDBC driver.
Syntax - mainprotocol : subprotocol
Example -
jdbc:oracle
jdbc:db2
jdbc:odbc
jdbc:oracle:thin          (Type 4)
jdbc:oracle:oci           (Type 2 Oracle call Interface)

2. IP address / hostname : IP address / hostname of the system in which database server is running.

3. Port Number : Port number is 16 bit integer number used to identify server. The default port no of Oracle is 1521 and MYSQL is 7070.

4. Resource : Database name / Service name

5. Username : Database username / in my system by default i will be working under scott.

6. Password : Database Password / in my system my scott user password is rakesh.


How to find Oracle Port number and service name ?

C:\Oracle\Product\10.2.0\db_1\network\ADMIN tnsnames.ora -----> Open this file


Program to Establish Connection to database

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Test3 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "rakesh");
System.out.println("Connection Established");
con.close();
}

}

Output -
Connection Established


No comments:

Post a Comment