Tuesday, December 23, 2014

Search Table Contents and Sort contents of a Table in java



Search Table Contents

import java.sql.*;
public class jdbcConn 
{
   public static void main(String[] args) throws Exception
      {
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","username","password");
      Statement stmt = con.createStatement();
      String query[] ={"Select * from emp where id=1", 
      "select name from emp where name like 'ravi_'",
      "select name from emp where name like 'ravi%'"};
      for(String q : query)
      {
         ResultSet rs = stmt.executeQuery(q);
         System.out.println("Names for query "+q+" are");
         while (rs.next()) 
         {
            String name = rs.getString("name");
            System.out.print(name+"  ");
         }
         System.out.println();
      }
   }
}

Sort contents of a Table

import java.sql.*;
public class jdbcConn
  {
   public static void main(String[] args) throws Exception
  {
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");
      Statement stmt = con.createStatement();
      String query = "select * from emp order by name";
      String query1="select * from emp order by name, job";
      ResultSet rs = stmt.executeQuery(query);
      System.out.println("Table contents sorted by Name");
      System.out.println("Id Name    Job");
      while (rs.next()) 
       {
         int id = rs.getInt("id");
         String name = rs.getString("name");
         String job = rs.getString("job");
         System.out.println(id + "  " + name+"   "+job);
      }
      rs = stmt.executeQuery(query1);
      System.out.println("Table contents after sorted by Name & job");
      System.out.println("Id Name    Job");
      while (rs.next()) 
      {
         int id = rs.getInt("id");
         String name = rs.getString("name");
         String job = rs.getString("job");
         System.out.println(id + "  " + name+"   "+job);
      }
   }
}

No comments:

Post a Comment