Go Back

Basic example of Java DataBase Connectivity | Java Connectivity | RDBMS | Java Programs

7/31/2021
All Articles

#Java # dataBase #Connectivity #JavaConnectivity #jdbc #JavaPrograms

Basic example of Java DataBase Connectivity | Java  Connectivity  |  RDBMS | Java Programs

Basic example of Java DataBase Connectivity

Java DataBase Connectivity is an API, as the name implies, it  help to achieve the  connectivity  between Java Programs & Database.

Also JDBC is “DB independent” i.e. Using JDBC we can interact with any RDBMS Applications in the world.

 

JDBC Pre-Requirement:

  • Install Any RDBMS Application (MySQL or oracle )

  • Create a “Database (Schema) “ by any name.

  • Create a table

  • Insert some data into the table.

Neccassary Steps to Work with Java DataBase Connectivity

  1. Loads the Driver.

  2. Get the DB Connection via Driver.

  3. Issue SQL Queries via Connection.

  4. Process the results returned by SQL Queries.

  5. Close All JDBC Objects.

 

Implementing Basic example of Java DataBase Connectivity :

 



package jdbc; 
import java.sql.*;
import java.sql.SQLException;

class MyFirstcode
{
    public static void main(String args[])
    {
    try
        {
        Class.forName("oracle.jdbc.OracleDriver");
        System.out.println("Driver loaded  successfully");
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//shubham-pc:1521/orcl","scott","tiger"); 
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("select ename,sal from emp");
        int total=0;
        int count=0;
        while(rs.next())
            {
                String str=rs.getString(1);
                int amt =rs.getInt(2);
                System.out.println(str+"\t"+amt);
                total=total+amt;
                ++count;
            }
            System.out.println("Average is "+(float)total/count);
       }
        catch(SQLException ex2)
        {
            System.out.println(" not connect to database:"+ex2.getMessage());
        }
        catch(ClassNotFoundException ex1)
        {
            System.out.println(" can not load driver:"+ex1.getMessage());
        }
    }
}    

Conclusion of Java DataBase Connectivity

Here we learn how to connect RDBMS using java program .
we see steps for connection between java and RDBMS Oracle and for execution our program we need to add jar file So
Right Click on the Java Project, where we want to make use of JAR File, select “Build Path” click on “Add External Archieves and select the “JAR File” & Click on “Open” .Finally We see JAR File under “Referenced Libraries.
Hope you like it subscribe our instagram and facebook account for more update .

Article