使用JDBC进行日期过滤

时间:2015-08-08 09:40:19

标签: java jdbc ucanaccess

date filtering - JDBCSQL

的正确格式是什么?

我一直在尝试将以下内容与MS-Access数据库

一起使用
SELECT doctorbusiness.dateofreport, 
       doctorbusiness.patientname, 
       doctorbusiness.labcomm, 
       doctorbusiness.xcomm, 
       doctorbusiness.spccomm, 
       doctorbusiness.ecgcomm 
FROM   doctorbusiness 
WHERE  doctorbusiness.doctorname = '"+selectedDoc+"' 
       AND (( doctorbusiness.dateofreport >= # "+sd+" # ) 
             AND ( doctorbusiness.dateofreport <= # "+ed+" # )) 

selectedDoc使用字符串,日期格式为sDeD

查询在MS-Access中运行良好,但出现以下异常:

net.ucanaccess.jdbc.UcanaccessSQLException: unknown token: 

更新

public void printDoctorIncome() {

    Date startDate = easypath.docB_startDate_jxdp.getDate();
    Calendar calSD = Calendar.getInstance();
    calSD.setTime(startDate); // convert your date to Calendar object
    int daysToDecrement = -1;
    calSD.add(Calendar.DATE, daysToDecrement);
    Date real_StartDate = calSD.getTime();
    SimpleDateFormat sdF1 = new SimpleDateFormat("dd-MM-yyyy");
    String sD = sdF1.format(real_StartDate);
    JOptionPane.showMessageDialog(null, sD);

    Date endDate = easypath.docB_endDate_jxdp.getDate();
    Calendar calED = Calendar.getInstance();
    calED.setTime(endDate); // convert your date to Calendar object
    int daysToIncrement = +1;
    calED.add(Calendar.DATE, daysToIncrement);
    Date real_endDate = calED.getTime();
    SimpleDateFormat sdF2 = new SimpleDateFormat("dd-MM-yyyy");
    String eD = sdF2.format(real_endDate);
    JOptionPane.showMessageDialog(null, eD);

    String selectedDoc = easypath.drname_jlist.getSelectedValue().toString();
    String sql = "SELECT doctorBusiness.dateofreport, doctorBusiness.patientName, doctorBusiness.labComm, doctorBusiness.xComm, doctorBusiness.spcComm, doctorBusiness.ecgComm FROM doctorBusiness WHERE doctorBusiness.doctorname ='"+selectedDoc+"' AND (doctorBusiness.dateofreport >= ?"+sD+"? AND doctorBusiness.dateofreport <= ?"+eD+"?)";
    try {
        conn = connectDB.getConnection();
        psmt = conn.prepareStatement(sql);
        rs = psmt.executeQuery();
        doctorIncome.docIncomePrint_table.setModel(DbUtils.resultSetToTableModel(rs));
        doctorIncome dI = new doctorIncome();
        dI.setVisible(true);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error");
        e.printStackTrace();
    }

}

这是我正在使用的代码

2 个答案:

答案 0 :(得分:3)

使用JDBC更好的方法是使用setDate/Time/Timestamp的{​​{1}}方法。你不应该关心具体数据库的日期格式。

PreparedStatement

答案 1 :(得分:1)

使用PreparedStatement是个好主意。但你也可以使用#MM / dd / yyyy#或#yyyy-MM-dd#(有或没有小时:分钟:秒)。

相关问题