SQLException捕获:' where子句'中的未知列

时间:2014-03-14 08:27:45

标签: javascript mysql servlets datepicker

我正在制作一个日历系统,我可以在两个日期之间进行选择,然后返回我在此期间工作了多少小时。下图为一天。日历系统如下所示:

  

DatePicker

如您所见,我有一个开始日期和结束日期。从javascript我应该拿起值并发送到我的servlet。

这是Javascript:

<script>

  $(function() {
        $(".datepicker" ).datepicker({dateFormat: 'yy-mm-dd'});
      });
  </script>

  </head>
<body>
    DatePicker Ajax Post:

    <form method="post" id="myForm" action="../getHoursSQL">
    Start Date:
        <input type="text" name="startDate" class="datepicker"/><br/>                     
    End Date:
        <input type="text" name="endDate" class="datepicker"/><br/>

        <input type="submit"/>
    </form>
    <div id="startresult"></div>
    <div id="endresult"></div>

</body>
<script type="text/javascript">

    $("input[name=endDate]").datepicker({
        dateFormat: 'yy-mm-dd',
        onSelect: function(date, instance){            
             var jsonStr = $('#myForm').serializeArray();
            console.log(JSON.stringify(jsonStr));
              $.ajax({
                  url: "../getHoursSQL",
                  type: "post",
                  data: JSON,
                  success: function(data){
                      start: $("#startDate").val();
                      alert("success");
                      $("#startresult").html(data);

                  },
                  error:function(){
                      alert("failure");
                      $("#startresult").html('there is error while submit');
                  }  
                });
        }
    });
</script>

我的servlet在这里:

import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
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 {
            //Load database driver
            Class.forName("com.mysql.jdbc.Driver");
            //Connection to the database
            connection = DriverManager.getConnection(connectionURL, "root", ""); 
            //Getting the data from database

            String sql = "SELECT *, (Day_hours + (Day_minutes / 60)) AS Allday_hours FROM Workdata "
                    + "WHERE startDate = ? AND endDate = ? ";
            PreparedStatement pst = connection.prepareStatement(sql);

            SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");

            java.util.Date util_StartDate = format.parse( req.getParameter("startDate") );  
            java.sql.Date sql_StartDate = new java.sql.Date( util_StartDate.getTime() );

            java.util.Date util_EndDate = format.parse( req.getParameter("endDate") );      
            java.sql.Date sql_EndDate = new java.sql.Date( util_EndDate.getTime() );
                pst.setDate( 1, sql_StartDate );
                pst.setDate(2, sql_EndDate );
                System.out.println(req.getParameter("startDate"));                          
                System.out.println(req.getParameter("endDate"));
            //Show the result from database
                ResultSet rs = pst.executeQuery();

            float Allday_hours_sum = 0;
                while (rs.next()){                                      
                    Allday_hours_sum += rs.getFloat("Allday_hours"); 

                }   
                res.setContentType("text/html;charset=UTF-8");          
                res.getWriter().print(Allday_hours_sum); 

                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){
            e.printStackTrace();
        }
        finally {

            try {
                if (connection != null) connection.close();
            }
            catch (SQLException ignored){
                System.out.println(ignored);
            }
        }
    }
}

所以问题是,当我运行我的页面时,我收到一个错误SQLException被捕获:未知列&#39; startDate&#39;在&#39; where子句&#39;中。我的数据库如下所示:

          P_id   |     Date         |   Day_hours    |        Day_minutes   |     Allday_hours  
Job 1      1        2014-03-10              4                      45                 4.45
Job 2      2        2014-03-10              5                      15                 5.15
Job 3      3        2014-03-09              3                      30                 3.30
Job 4      4        2014-03-09              1                      45                 1.45

                                                                   Printet out:     **15.15**

这当然是因为我没有任何&#34; startDate&#34;在我的数据库中。但是,如何进行以下SQL查询以获取日期?

String sql = "SELECT *, (Day_hours + (Day_minutes / 60)) AS Allday_hours FROM Workdata "
                        + "WHERE startDate = ? AND endDate = ? ";

当我点击&#34;提交&#34;我在我的控制台中得到了这个主题:

2014年3月3日 2014年3月21日

SQLException caught: Unknown column 'startDate' in 'where clause'

4 个答案:

答案 0 :(得分:2)

您需要在WHERE关键字之前添加空格,如下所示

String sql = "SELECT *, (Day_hours + (Day_minutes / 60)) AS Allday_hours FROM Workdata "
                    + " WHERE Date Between ? AND ? ";

答案 1 :(得分:0)

正确答案是:

String sql = "SELECT *, (Day_hours + (Day_minutes / 60)) AS Allday_hours FROM Workdata "
                    + " WHERE Date = ? AND Date = ? ";

答案 2 :(得分:0)

您的表格中没有名称为startDateendDatedate的列。 因此抛出了SQL Exception。

更改:

String sql = "SELECT *, (Day_hours + (Day_minutes / 60)) AS Allday_hours
              FROM Workdata "
           + "WHERE startDate = ? AND endDate = ? ";

致:

String sql = "SELECT *, (Day_hours + (Day_minutes / 60)) AS Allday_hours
              FROM Workdata "
           + "WHERE Date = ? AND Date = ? ";

当您只有Date列时,您无法在AND子句中使用where
它永远不会发生。

您必须在 子句中寻找 - 或

示例
变化:

WHERE Date = ? AND Date = ?  

致:

WHERE Date IN ( ?, ? )

或者

WHERE Date between ? and ?

答案 3 :(得分:0)

WHERE子句传递两个变量。尝试将其称为{0}{1},或使用javascript startDateendDate中的名称。

WHERE Date BETWEEN {0} and {1}

或,

WHERE Date BETWEEN startDate AND endDate