Reputation: 63
I am working on a script which is supposed to store the entire fetched table into a hashmap. So far, I have been able to fetch the records from MySQl database, but i am unable to store and display the records from the hashmap. Please guide me to a correct code for the same.
The code so far:
public class myRow {
private int id;
private String name;
private int level;
private int m1;
private int m2;
private int m3;
// the constructor
public myRow( String n, int l,int m1, int m2, int m3) {
this.name = n;
this.level = l;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
}}
The main class is as follows:
public static void main(String[] args){
Connection conn = null;
Statement stmt1 = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Connecting to database...\n\n");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt1 = conn.createStatement();
Map<Integer, myRow> map = new HashMap<Integer, myRow>(0);
try {
String sql="SELECT * FROM recs.new_table;";
System.out.println(sql);
ResultSet rs = stmt1.executeQuery(sql);
while(rs.next()){
myRow mr = new myRow(rs.getString(2), rs.getInt(3),rs.getInt(4),rs.getInt(5),rs.getInt(6) );
map.put(rs.getInt(1), mr);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
System.out.println(map);
System.out.println(map.containsValue("mark"));
}catch(Exception e){
System.out.println(" ERROR :: "+e);
}
The table records are in the following manner:
Upvotes: 0
Views: 3591
Reputation: 3250
The code looks ok to me, except for the line:
System.out.println(map.containsValue("mark"));
This will not find the row containing mark
. The containsValue
relies on the object's equals
method, and since you're passing a simple string, a String
class object will never equal a myRow
class so it will never find it.
To locate one of the rows in the map, you'll need some code like:
myRow findRowByName(String name) {
for (myRow row : map.values()) {
if (row.name.equals(name)) {
return row;
}
}
}
Upvotes: 1