JDBC – Connection to DB

Connection to Database from Java Application:

  • DriverManager class belongs to sql package.
  • DriverManager providing getConnection() method.
  • getConnection() method returns connection object if the input values are valid

Input values are:

  • String url = “jdbc:oracle:thin:@localhost:1521:xe”;
  • String uname = “system”;
  • String pwd = “admin”;

Invoke method:

  • Connection con = DriverManager.getConection(url, uname, pwd);

Go through briefly if you want:

  • Connection URL: The connection URL for the oracle database is like jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. You may get all these information from the tnsnames.ora file.
  • Username: The default username for the oracle database is system.
  • Password: It is the password given by the user at the time of installing the oracle database.
package online;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection
{
            public static void main(String args[]) throws SQLException
            {
                        String driver = “oracle.jdbc.driver.OracleDriver”;
                        Connection conn = null;
                        try
                        {
                                    Class.forName(driver);
                                    System.out.println(“Driver loaded”);
                                   
                                    String url = “jdbc:oracle:thin:@localhost:1521:xe”;
                                    String uname = “system”;
                                    String pwd = “admin”;
                                    conn = DriverManager.getConnection(url, uname, pwd);
                                    System.out.println(“Connection is ready”);
                        }
                        catch(ClassNotFoundException e1)
                        {
                                    System.out.println(“Exception : Driver is not present”);
                        }
                        finally
                        {
                                    if(conn != null)
                                    {
                                                conn.close();
                                                System.out.println(“Connection closed”);
                                    }
                        }
            }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top