Question

I have a Servlet where I want to loop through my COLUMN "Allday_hours" in my MySQL database. Right now I only get the first COLUMN out printer out, but I want to loop through all the COLUMNS and ADD them together. Does anybody knows how to do that in my Servlet?

As you might can see the Day_hours and Day_minutes is equal to Allday_hours added together.

I have a video of it here: https://www.youtube.com/watch?v=Ju-qLXmf1-Q&feature=youtu.be

Best Regards Mads

package WorkPackage;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/getHoursSQL")
public class getHoursSQL extends HttpServlet{

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException{

        String connectionURL = "jdbc:mysql://localhost/NekiWork";
        Connection connection=null;


        try {

            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(connectionURL, "root", ""); 
            String sql = "SELECT *, (Day_hours + (Day_minutes / 100)) AS Allday_hours FROM Workdata";
            PreparedStatement pst = connection.prepareStatement(sql);

            ResultSet rs = pst.executeQuery(sql);
            String all_day_hours = null;    

            if(rs.next()){                                      
                 all_day_hours = rs.getString("Allday_hours");  
            }       
            res.setContentType("text/html;charset=UTF-8");          
            res.getWriter().write(all_day_hours);   
            pst.close();

        }
        catch(ClassNotFoundException e){

            System.out.println("Couldn't load database driver: " + e.getMessage());
        }
        catch(SQLException e){
            System.out.println("SQLException caught: " + e.getMessage());
        }
        catch (Exception e){
            System.out.println(e);
        }
        finally {

            try {
                if (connection != null) connection.close();
            }
            catch (SQLException ignored){
                System.out.println(ignored);
            }
        }
    }
}
Était-ce utile?

La solution

What I understood that the only first row is printing with the following code

It's may be because of loop you have specified try using this

  float Allday_hours_sum = 0;
 while (rs.next()){                                      
   Allday_hours_sum += Float.parseFloat (rs.getString("Allday_hours"));  
      }       

And print Allday_hours_sum

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top