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:
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:

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Get Column Value Using Collection Classes
Post your Comment