JAVA - How To Populate a HashMap From MySQL DataBase In Java

JAVA - How To Get Data From MySQL Database To HashMap In Java


java hashmap mysql database

In this java Collection Tutorial we will see How To retrieve data from MySQL database
using HashMap In Java NetBeans .

maybe you need to see:
   - connect java to mysql.
   - using HashMap.





Project Source Code:

package javaapp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

// create a users class
class Users{
    private int Id;
    private String Fname;
    private String Lname;
    private int Age;
    
    public Users(){}
    public Users(int id, String fname,String lname,int age){
        this.Id = id;
        this.Fname = fname;
        this.Lname = lname;
        this.Age = age;
    }
    
    public int getId(){
        return this.Id;
    }
    
    public String getFname(){
        return this.Fname;
    }
    
       public String getLname(){
        return this.Lname;
    }
       
     public int getAge(){
        return this.Age;
    }
     
     // create a tostring method to diplay data
     public String ToString(){
         return this.Id+" "+this.Fname+" "+this.Lname+" "+this.Age;
     }
}


public class Work {
   
    // create a method to get the connection
    public static Connection getConnection(){
        
        Connection con = null;
        
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test_db", "root", "");
        } catch (SQLException ex) {
            Logger.getLogger(Work.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return con;
    }
    
    public static void main(String[] args){

        // create the hashmap
        HashMap<Integer,Users> map = new HashMap<Integer,Users>();
        
        Statement st = null;
        ResultSet rs = null;
        Connection con = getConnection();
        Users u;
        
        try{
            st = con.createStatement();
            rs = st.executeQuery("SELECT * FROM users");
            while(rs.next()){
                Integer id = rs.getInt("id");
                String fname = rs.getString("fname");
                String lname = rs.getString("lname");
                int age = rs.getInt("age");
                
                u = new Users(id, fname,lname,age);
                
                // set data in the hashmap
                map.put(id, u);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        
        // display data from the hashmap
        for(Integer i : map.keySet()){
            Users us = map.get(i);
            System.out.println(us.getId()+" "+us.getFname()+" "+us.getLname()+" "+us.getAge());
        }
        
        // show data from hashmap using our ToString Method
        System.out.println("______With ToString______");
        for(Integer i : map.keySet()){
            Users us = map.get(i);
            System.out.println(us.ToString());
        }
        
        // now your data are displayed from mysql database using hashmap 
    }
}

///////////////OUTPUT:
1 Fuser_1 Luser_1 56
2 Fuser_2 Luser_2 26
4 ftest ltest 43
5 DBB BDD 14
6 hgjk sdfr 25
7 some thing 32
8 white black 42
9 AAA1 BBB1 32
10 WOR HOME 54
13 java csharp 66
14 ASP.NET JAVAEE 11
15 FN LN 40
______With ToString______
1 Fuser_1 Luser_1 56
2 Fuser_2 Luser_2 26
4 ftest ltest 43
5 DBB BDD 14
6 hgjk sdfr 25
7 some thing 32
8 white black 42
9 AAA1 BBB1 32
10 WOR HOME 54
13 java csharp 66
14 ASP.NET JAVAEE 11
15 FN LN 40



Share this

Related Posts

Previous
Next Post »

2 comments

comments
Anonyme
14 décembre 2023 à 00:44 delete

public static Map citesteMagazine(Connection connection) throws SQLException {
Map magazinMap = new HashMap<>();

String sqlMagazine = "SELECT * FROM magazin";
try (Statement statement = connection.createStatement();
ResultSet resultSetMagazine = statement.executeQuery(sqlMagazine)) {

while (resultSetMagazine.next()) {
int idMagazin = resultSetMagazine.getInt("id");
String numeMagazin = resultSetMagazine.getString("nume");
String adresaMagazin = resultSetMagazine.getString("adresa");

Set produse = citesteProduse(connection, idMagazin);

Magazin magazin = new Magazin(idMagazin, numeMagazin, adresaMagazin, produse);
magazinMap.put(idMagazin, magazin);
}
}

return magazinMap;
}

public static Set citesteProduse(Connection connection, int idMagazin) throws SQLException {
Set produse = new HashSet<>();

String sqlProduse = "SELECT * FROM produs WHERE id_mag = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sqlProduse)) {
preparedStatement.setInt(1, idMagazin);

try (ResultSet resultSetProduse = preparedStatement.executeQuery()) {
while (resultSetProduse.next()) {
int idProdus = resultSetProduse.getInt("id");
String numeProdus = resultSetProduse.getString("nume");
int vechime = resultSetProduse.getInt("vechime");

Produs produs = new Produs(idProdus, numeProdus, vechime);
produse.add(produs);
}
}
}

return produse;
}

public static void afiseazaMagazine(Map magazinMap) {
for (Magazin magazin : magazinMap.values()) {
System.out.println(magazin);
}
}
Map magazinMap = citesteMagazine(connection);
afiseazaMagazine(magazinMap);

Reply
avatar