Wednesday, 11 December 2013

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

import java.sql.*;//jdbc api
//import com.mysql.jdbc.*;
public class SelectTest1
{
 public static void main(String args[]) throws Exception
 {
 // try
 // {
    //load the jdbc driver class
 //   Class.forName("com.mysql.jdbc.Driver");
    com.mysql.jdbc.Driver dr=new 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();

// }
// 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 SelectTest1.java
D:\jdbc>java SelectTest1
*/

No comments:

Post a Comment