如何格式化 SQL DATETIME 以将其映射到给定日期并检索一条记录



嗨,必须检索数据库的一条记录,该记录应尽可能接近我的参数(日期(YYYY-MM)),请记住,数据库(sql服务器)中的列是DATETIME,所以我需要格式化它以便我可以比较它,这是我一直在做的事情:

public Document findByDate(String date) throws GeneralException{
    Document docs = new Document();
    String d1 = date;
    String delimiter = "-";
    String[]temp = d1.split(delimiter);     
    try{
        String sql = "SELECT TOP(1) *  FROM Document  WHERE issueDate >= '" +   temp[1]+ temp[0] +"'  AND issuedate < '"+ temp[1]+ temp[0] +"'  ORDER BY issueDate DESC ";
        ResultSet rs = this.executeQuery(sql);
        while(rs.next()){
            docs = (Document) this.build(rs);
        }
        if(docs != null){
            return docs;
        } else {
            return docs = null;
        }
    } catch (SQLException ex){
        throw new GeneralException(ex);
    }
}

谢谢

不应使用字符串串联将参数传递给查询。这容易出错,依赖于数据库和区域设置,并且使您的代码容易受到 SQL 注入攻击。相反,请使用预准备语句,并将日期参数作为java.sql.Date传递,而不是将其作为字符串传递:

String sql = 
    "SELECT TOP(1) * FROM Document WHERE issueDate >= ? AND issuedate < ? ORDER BY issueDate DESC";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setDate(1, date);
stmt.setDate(2, date);
ResultSet rs = stmt.executeQuery();

也就是说,我不明白您的查询如何工作。数据库中的日期如何既小于或等于给定日期,又大于同一日期?也许您应该使用日期作为最低界限,并将日期 + 1 个月作为上限?

所以你想要的是同月或上个月的最新记录,当然我们必须记住,十二月的前一个月是去年......

您可能会乱想比较月份和年份,但是如果不是在该月底通过YYYY-MM,那么它只是

Select Top(1) * from Documents Where IssueDate <= ? Order By IssueDate Desc

月底在哪里 ?

尝试此查询

SELECT TOP(1) *  FROM Document  WHERE convert(date,issueDate) >= ' datevalue ' AND convert(date,issuedate) < ' datevalue '  ORDER BY issueDate DESC 

最新更新