我正在编写一个脚本,该脚本应该将整个获取的表存储到 HashMap 中。到目前为止,我已经能够从 MySQl 数据库中获取记录,但无法存储和显示 HashMap 中的记录。 请指导我找到正确的代码。
到目前为止的代码:
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;
}}
主要类如下:
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);
}
最佳答案
代码对我来说看起来不错,除了这一行:
System.out.println(map.containsValue("mark"));
这不会找到包含mark
的行。 containsValue
依赖于对象的 equals
方法,并且由于您传递的是简单字符串,因此 String
类对象永远不会等于 >myRow
类,因此它永远找不到它。
要找到 map 中的某一行,您需要一些代码,例如:
myRow findRowByName(String name) {
for (myRow row : map.values()) {
if (row.name.equals(name)) {
return row;
}
}
}
关于java - 获取sql记录并存储在hashmap中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32209625/