Reputation: 349
I've got a method, that returns the value of a ResultSet query via a date object. The snag is that, in my output, it only returns the last value in the particular column. How do i go about this?
public Date getTime(){
Date date = null;
DateFormat format;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM error_log WHERE service_source = 'Billbox' ");
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
}
con.close();
} catch (Exception ex) {
Logger.getLogger(LogDB.class.getName()).log(
Level.SEVERE, null, ex);
}
return date;
}
Then in my main method:
public static void main(String args[]){
TestA ea = new TestA();
Date ss = ea.getTime();
System.out.println(ss);
}
But this only returns the last value in my query. how can i print out other (the olders) along with it?
Upvotes: 0
Views: 162
Reputation: 12524
just:
List<Date> lDateDb = new ArrayList<Date>();
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
lDateDb.add(date);
}
return lDateDb;
change return type of getTime
to List<Date>
and change the main to:
public static void main(String args[]){
TestA ea = new TestA();
List<Date> lAllDate = ea.getTime();
for (Date lDate : lAllDate)
System.out.println(lDate );
}
Upvotes: 0
Reputation: 5087
Because of the while loop you asign to date the last value. Change your method as
public List<Date> getTime(){
You can try
List<Date> dates = new ArrayList<Date>();
and then inside your while loop;
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
dates.put(date);
}
return dates;
Upvotes: 1
Reputation: 1605
You need to fill a list of dates from your query results. Try this :
public List<Date> getTime(){
List<Date> dates = new ArrayList<Date>();
DateFormat format;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM error_log WHERE service_source = 'Billbox' ");
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
dates.add((Date)format.parse(ds));
}
con.close();
} catch (Exception ex) {
Logger.getLogger(LogDB.class.getName()).log(
Level.SEVERE, null, ex);
}
return dates;
}
Upvotes: 2