简体   繁体   English

WHERE子句中的MySQL陈述式错误

[英]Error in MySQL statement in WHERE clause

I am trying to get a value "startDate" and "endDate" from my form: 我正在尝试从表单中获取值“ startDate”和“ endDate”:

<form>
        <input id="startDate"/>                     
        <input id="endDate"/>
    </form

The form is connected to a javascript, which from there goes to a MySQL database. 表单已连接到JavaScript,然后从JavaScript进入MySQL数据库。 The problem is that every time I run SQL query in my servlet i get the following error: 问题是每次我在servlet中运行SQL查询时,都会出现以下错误:

SQLException caught: Unknown column 'startDate' in 'where clause' 捕获SQLException:“ where子句”中的未知列“ startDate”

Can anybody see what I am doing wrong? 有人可以看到我在做什么吗? have a nice day from Julie 从朱莉过得愉快

EDITED CODE: I have tried to edited my code. 编辑的代码:我试图编辑我的代码。 I now get the error at: Date startDate; 现在,我在以下位置收到错误:Date startDate; , where it says: "Duplicate local variable startDate". ,显示为:“重复的局部变量startDate”。 That is of course because I have String startDate = req.getParameter("startDate"); 那当然是因为我有String startDate = req.getParameter(“ startDate”); . I dont have to use this anymore? 我不必再使用了吗? package WorkPackage; 打包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;
        String startDate = req.getParameter("startDate");
        String endDate= req.getParameter("endDate");
        try {
            //Load database driver
            Class.forName("com.mysql.jdbc.Driver");
            //Connection to the database
            connection = DriverManager.getConnection(connectionURL, "root", ""); 
            //Getting the data from database
            Date startDate;                                             
            String sql = "SELECT *, (Day_hours + (Day_minutes / 60)) AS Allday_hours FROM Workdata WHERE Date = ?";
            PreparedStatement pst = connection.prepareStatement(sql);
                pst.setDate(1,startDate);
                //pst.setString(2,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){
            System.out.println(e);
        }
        finally {

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

EDITED: This is how my database looks like: http://postimg.org/image/3sbzplg9d/ 编辑:这是我的数据库的样子: http : //postimg.org/image/3sbzplg9d/

This is my javascript where I am getting some values out from my calendar: 这是我的JavaScript,可以从我的日历中获取一些值:

<form>
        <input id="startDate"/>                     
        <input id="endDate"/>
    </form>
    <div id="startresult"></div>
    <div id="endresult"></div>
    <script>

    $(function(){
        $("#startDate").datepicker({
            dateFormat: 'yy-mm-dd',
            onSelect: function(dateText,inst){
                $('.selected-date').html(dateText);

                $.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');
                      }  
                    });
            }
        });
    });

    $(function(){
            $("#endDate").datepicker({
                dateFormat: 'yy-mm-dd',
                onSelect: function(dateText,inst){
                    $('.selected-date').html(dateText);

                    $.ajax({
                          url: "../getHoursSQL",
                          type: "post",
                          data: JSON,
                          success: function(data){
                              end: $("#endDate").val();
                              alert("success");
                              $("#endresult").html(data);
                          },
                          error:function(){
                              alert("failure");
                              $("#result").html('there is error while submit');
                          }  
                        });
                }
            });
        });

</script>

As mentioned in the error it couldn't find the column in the table. 如错误所述,它无法在表中找到该列。 Please check your table Workdata has field startDate 请检查您的表Workdata是否具有字段startDate

And also it is not good to pass date as String and also be careful to use = operator to compare date or datetime filed. 另外,将日期作为String传递也是不好的,也要小心使用=运算符比较提交的日期或日期时间。 My advise is to compare datetime use BETWEEN operator. 我的建议是比较使用BETWEEN运算符的日期时间。

... WHERE startDate BETWEEN value1 AND value2

if you want to get data then you should this instead. 如果您想获取数据,则应该这样做。

Date startDate;
//use SqlDate instead of string.

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

Now you have something in your output as you have date column in your table. 现在,由于表中有date列,因此输出中已有内容。

UPDATE : 更新:

If you want to use String datatype for date parameter.. Remove Date startDate and keep it what you have.. After that Parse your date using SimpleDateFormatter. 如果要对日期参数使用String数据类型。.删除Date startDate并保留它的内容。.之后,使用SimpleDateFormatter解析日期。

For EG. 对于EG。

String startDate = req.getParameter("Date");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//surround below line with try catch block as below code throws checked exception
Date start = sdf.parse(startDate);
out.println(sdf.format(startDate)); //this is what you want yyyy-MM-dd  

Thanks.. 谢谢..

As far as I can tell from your image (it's rather cluttered, far too much information) there's no column called startDate in table Workdata. 据我从您的图像可以看出(它很混乱,信息太多),在表Workdata中没有名为startDate的列。 All columns in an SQL statement must actually exist in the appropriate tables. SQL语句中的所有列实际上必须存在于适当的表中。

Did you mean column Date? 您是指日期列吗? If you did, you shouldn't use 如果这样做,则不应使用

pst.setString(1, startDate);

because that's only good for setting string columns (varchar, longtext, etc). 因为这仅适用于设置字符串列(varchar,longtext等)。 Instead, you should use 相反,您应该使用

pst.setDate(1, startDate);

where startDate here is a java.sql.Date , not a String 这里的startDatejava.sql.Date ,而不是String

EDIT: 编辑:

In response to your updates, I have updated my answer. 为了回应您的更新,我已经更新了我的答案。

The line 线

Date startDate;

surely won't compile, as startDate is already a declared as a String. 肯定不会编译,因为startDate已经被声明为String。 Even if you changed the name, you have not set the date given in the request parameter. 即使更改了名称,也没有设置request参数中给定的日期。

You'll need to do something like this: 您需要执行以下操作:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = format.parse(req.getParameter("startDate"); 
pst.setDate(1,startDate);

You'll need to change the string in the SimpleDateFormat constructor to suit your needs (the format of your date string). 您需要在SimpleDateFormat构造函数中更改字符串以适合您的需要(日期字符串的格式)。 The above code will work for dates formatted like 2014-03-11. 上面的代码适用于格式为2014-03-11的日期。 Your format might be different. 您的格式可能不同。 See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html 参见http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM