SELECT col_name1, col_name2, col_name3 from Table_Name;
I am using above SQL query and I have to get all the values in col_name3 which has more than 5 value.
I am using :
while(rs.next()){
String value1 = rs.getString("col_name3");
String value2 = rs.getString("col_name3");
}
But all value in the String value1 and value2 is the last value of the col_name3. Why?
If you want to get only the result of one columns then you can use a List<String>
List<String> list = new ArrayList<>();
while(rs.next()){
list.add(rs.getString("col_name3"));
}
If you want to get all your columns then you need to change the type of your list to your Object :
List<MyObject> list = new ArrayList<>();
while(rs.next()){
list.add(new MyObject(rs.getString("col_name1"), rs.getString("col_name2"), rs.getString("col_name3")));
}
You can create a class that contain all the columns of your Object for example :
Class MyObject{
private String col1;
private String col2;
private String col3;
//Constructor
public MyObject(String col1, String col2, String col3){
this.col1 = col1;
this.col2 = col2;
this.col3 = col3
}
//getter and setters
}
EDIT
If you want to show your information you have two ways first like @Mick Mnemonic said in comment override toString()
in your class MyObject like this :
@Override
public String toString() {
return "MyObject{" + "col1=" + col1 + ", col2=" + col2 + ", col3=" + col3 + '}';
}
and your loop should look like this :
for(int i = 0; i<list.size; i++){
System.out.println(list.get(i));
}
Or you can get element by element :
for(int i = 0; i<list.size; i++){
System.out.println(list.get(i).getCol1() + " " + list.get(i).getCol2());
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments