在MySQL和Servlet中循环通过COLUMN

时间:2014-03-09 08:19:21

标签: mysql loops calculated-columns

我有一个Servlet,我想在我的MySQL数据库中遍历我的COLUMN“Allday_hours”。现在我只得到第一台COLUMN打印机,但我想循环遍历所有的COLUMNS并将它们一起添加。有人知道如何在我的Servlet中这样做吗?

您可能会看到Day_hours和Day_minutes等于Allday_hours加在一起。

我在这里有一个视频: https://www.youtube.com/watch?v=Ju-qLXmf1-Q&feature=youtu.be

最诚挚的问候 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);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

据我所知,唯一的第一行是使用以下代码进行打印

这可能是因为你指定的循环尝试使用此

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

打印Allday_hours_sum