开发者

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

开发者 https://www.devze.com 2023-03-22 17:29 出处:网络
When I run a query it returns the following results periodEndingDate | TotalMin | TimesheetId | -------------------------------------------

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 Num开发者_如何学Cber 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


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.


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);  
}


Why cant you just do:

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

What am I missing?

0

精彩评论

暂无评论...
验证码 换一张
取 消