user710502
user710502

Reputation: 11471

How do I pass the data to a ResultSet from a MySQL Query?

When I run a query it returns the following results

periodEndingDate | TotalMin | TimesheetId |
-------------------------------------------
2007-08-19       |  38.000  |            1|
2010-09-17       |  26.500  |            2|

So, I have the following way of getting the values, I know the third one is getting it right (The Number one) but how can I cast to the second and first columns ? (Date) and (Float or Double), the TotalMin is an addition of several columns (minutes) of ints divided by 60.

This is what I have

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT periodEndingDate, 
              ((minutesMon+minutesTue+minutesWed+minutesThu+"
              +"minutesFri+minutesSat+minutesSun)/60) as TotalMin, 
              TimesheetId FROM timesheet WHERE employeeID='"+empID+"';");

for (; rs.next();) {
                ArrayList tmData = new ArrayList();
                tmData.add((String) rs.getObject(1));

                tmData.add((String) rs.getObject(2));

                                       //for the timesheet id
                tmData.add(((Number) rs.getObject(3)).intValue()); 

                TimeSheetData.add(tmData);
            }

Thank you

Upvotes: 2

Views: 164

Answers (3)

Shahzeb
Shahzeb

Reputation: 4785

Hope this is what you are after

Create a class

class Timesheet
    {
        //periodEndingDate | TotalMin | TimesheetId 
        private Date periodEndingDate;
        private BigDecimal totalMin;
        private int timesheetId;

        //---------GETTERS AND SETTERS
    }

Then in your code above replace for loop with this

List<Timesheet> tmData = new ArrayList<Timesheet>();
    while (rs.next()) {
        Timesheet timesheet = new Timesheet();
         //periodEndingDate,TotalMin and TimesheetId should be the name of columns in the table  
        timesheet.setPeriodEndingDate( rs.getDate("periodEndingDate"));
        timesheet.setTotalMin( rs.getBigDecimal("TotalMin"));
        timesheet.setTimesheetId(rs.getInt("TimesheetId"));
        tmData.add(timesheet);  
}

Upvotes: 1

Tom Studee
Tom Studee

Reputation: 10452

Why cant you just do:

tmData.add((DateTime) rs.getObject(1));
tmData.add((decimal) rs.getObject(2));

What am I missing?

Upvotes: 0

Kal
Kal

Reputation: 24910

You can use rs.getDate() or rs.getTimestamp() for the first column.

You can use rs.getDouble() for the second one.

This is better than using rs.getObject() and then casting it. I'd change your 3rd column to rs.getInt()

Note : rs.getInt() and rs.getDouble() return primitives that get autoboxed when they are added to your list.

Upvotes: 4

Related Questions