Sample program to connect database with JAVA using JDBC

Introduction


In previous lesson, we learn about JDBC and purpose of JDBC,how to use.Here we are making a sample program which connects to a database and execute a small select query and prints the output.

Pre-requisites

  • JDK installed in your computer and check your classpath.
  • JDBC jar required.Add classes12.jar to your class path, because in the following program i am using oracle data source connection.
  • Install oracleXE in your system and SID should be XE.
  • create a user with name "abc" and password "abc"
  • create a table with name table1 in abc user and create fields id as number and name as varchar and sal as long.
  • insert some dummy data into it.

Sample program to connect database with JDBC



package friends;

import java.sql.*;
import oracle.jdbc.pool.OracleDataSource;

class JDBCSample
public Connection con = null;

 
       public void connect(String username, String password)
   {
try
{
OracleDataSource odsn = new OracleDataSource();
odsn.setURL("jdbc:oracle:thin:"+username+"/"+password+"@127.0.0.1:1521:XE");
con=odsn.getConnection();
  if(con!=null)
   System.out.println("Connected successfully to database..............:");
   else
    System.out.println("Unable to open Database connection....");
   
}
catch (SQLException e)
{
   System.out.println("Unable to open Database connection...." + e);
}
   }

   public void close()
   {
try
{
   if (con != null)
   {
con.close();
   }
}
catch (SQLException e)
{
   System.out.println("Unable to close Database connection...." + e);
}
   }



public void executeQuery() throws SQLException {
     Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM table1");

    while (rs.next()) {
        int id= rs.getInt(1);
        String name = rs.getString(2);
        float sal = rs.getFloat(3);
        
        System.out.println("id id"+id);
        System.out.println("name is"+name);
        System.out.println("sal is"+sal);

    }
}

public static void main(String[] args) {
JDBCSample je=new JDBCSample();
try
{

je.connect("abc","abc");
je.executeQuery();
je.close();

}
catch(Exception e)
{
System.out.println("error s "+e);
}

}


}

The above program retrieves data from the table table1 in XE database and prints in the console.
If you are facing any problem with the above program feel free to post your questions here.
The road gladdens the obsessed ghost.

0 comments:

Post a Comment