Wednesday, 11 December 2013

jdbc program for retrieving the values (data) from the database using MySql

import java.sql.*;//jdbc api
public class SelectTest
{
 public static void main(String args[])
 {
  try
  {
    //load the jdbc driver class
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("jdbc driver is registered with Driver manager Service");

   //establish the connection with DB SW
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","admin");
    System.out.println("connection is established with D/B S/W");
    //create the statement object
    Statement st=con.createStatement();
    System.out.println("statement object is ready ");
    //send query to db s/w make a query executing in db s/w and get result

    ResultSet rs=st.executeQuery("select * from students");
    System.out.println("query executed in db s/w & ResultSet object is created");
   //process the ResultSet object and display the student
   while(rs.next())
   {
    int n=rs.getInt("stid");
    String s=rs.getString("sname");
    String addr=rs.getString("sadd");
    System.out.println(n+"  "+s+"  "+addr);
   }
   System.out.println("Result set is displayed");
  //close the jdbc stream objects
   rs.close();
   st.close();
   con.close();
   System.out.println("jdbc stream objects are closed");
  //to know the class names of jdbc objects
   System.out.println("classname of st obje="+st.getClass().getName());
   System.out.println("classname of con obje="+con.getClass().getName());
   System.out.println("classname of rs obje="+rs.getClass().getName());
 }
 catch(ClassNotFoundException cnf)
 {
  cnf.printStackTrace();
 }
 catch(SQLException se)
 {
  se.printStackTrace();
 }
 catch(Exception e)
 {
  e.printStackTrace();
 }
}
}
/*
D:\jdbc>set classpath=D:\softwares\MySQL\new\mysql-connector-java-5.1.18-bin.jar;.;
D:\jdbc>javac SelectTest.java
D:\jdbc>java SelectTest
*/

No comments:

Post a Comment