Get Column Value Using Collection Classes

The HashSet class implements the Set interface which holds the iteration element of the set.

Get Column Value Using Collection Classes

The HashSet class implements the Set interface which holds the iteration element of the set.

Get Column Value Using  Collection Classes

Get Column Value Using  Collection Classes

     

This application illustrates how to retrieve data from mysql table using HashSet class.

The HashSet class implements the Set interface which holds the iteration element of the set. In this example we are using the java.util package to extends this class. There are four type of constructor available in this class:

  • HashSet ():- This HashSet Constructs a new, empty set. 
  • HashSet (Collection<? extends E> c):- This HashSet Constructs a new set containing the elements in the specified collection. 
  • HashSet (int initialCapacity):- Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor.
  • HashSet (int initialCapacity, float loadFactor):- Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.

 

The Source Code of Employee.java

 

import java.sql.*;
import java.util.*;

public class Employee{
  private String name;
  private String lastAccess;
  private int id;

  public String getName () {
  return (name);
  }
  public void setName (String name){
  this.name = name;
  }

  public String getLastAccess (){
  return (lastAccess);
  
  public void setLastAccess (String lastAccess){
  this.lastAccess = lastAccess;
  }

  public int getId() {
  return (id);
  }
  public void setId (int id){
  this.id = id;
  }

  public static void main(String[] args) {
  System.out.println("\nGetting All Rows from a table!\n");
  Connection con = null;
  String url = "jdbc:mysql://localhost:3306/";
  String db = "test";
  String driver = "com.mysql.jdbc.Driver";
  String user = "root";
  String pass = "root";
  ArrayList list = new ArrayList();
  Employee emp;
  int count =0;

  try{
  Class.forName(driver).newInstance();
  con = DriverManager.getConnection(url+db, user, pass);
  Statement stmt = con.createStatement();
  ResultSet rs = stmt.executeQuery("select *from emp");
  System.out.println("Emp_Id" "\t " "Emp_name" "\t" "Access_Time");
  
  while (rs.next()) {
  count++;
  emp = new Employee ();
  emp.setId(rs.getInt("id"));
  emp.setName(rs.getString("name"));
  emp.setLastAccess(rs.getString("lastAccess"));
  list.add(emp);
  }
  
  ListIterator li = list.listIterator();
  
  while (li.hasNext()){
  Employee emp1=(Employee)li.next();
  System.out.print(emp1.getId()+"  ");
  System.out.print(emp1.getName()+"\t");
  System.out.print(emp1.getLastAccess());
  System.out.print("\n");
  }  
  rs.close();
  stmt.close();
  con.close();
  catch (Exception e) {
  e.printStackTrace();
  }
  }
}

 

Output:

 

Download Source Code