Connect database to Java program

Q. Write a program to establish the connection between Java program to database.


In this example we establish the connection between database to Java program.

We are using type 4 driver to connect the Oracle database to Java program. The DriverManager class is used to establish the connection. The Connection object has the connection URL, username, password.

The sysdate command is used in SQL to print current date.

import java.sql.*;
class JDBCConnection
     public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
     public static final String DBUSER = "local";
     public static final String DBPASS = "test";
     public static void main(String args[])
               //Load the driver
               //Cretae the connection object
               Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
               //Create the Statement Object
               Statement stmt = con.createStatement();
               //Excute the SQL query
               ResultSet rs = stmt.executeQuery("Select sysdate from dual");
               if (con != null)
                    System.out.println("Connection is established.\n");
                    while (
                         System.out.println ("Current Date is: "+rs.getDate(1));
                    System.out.println("Connection is not esablished");
               //Closing the connection object
          catch(Exception ex)


java connection