使用JDBC在SQL中的日期之间进行搜索?

我目前正在编写一个Java Swing应用程序,它从MYOB数据库文件中读取数据并在表格中显示某些信息。 我已经能够成功生成所需的SQL语句,但是我无法添加日期之间的搜索function(我们的数据库非常大,所以我们试图限制结果)。 我的一个查询的示例如下(用Java编写):

rs = stmt.executeQuery("SELECT sales.InvoiceNumber, sales.ShipToAddress, sales.Date " + "FROM sales, customers " + "WHERE sales.CardRecordID = customers.CardRecordID " + "AND customers.Name = 'Cash Sales' " + "ORDER BY sales.ShipToAddress ASC, sales.Date DESC" + ";"); 

我有两个日期(它们实际上是Java中的字符串,但格式为dd / MM / yyyy)。

我尝试在我的WHERE使用另一个AND子句与BETWEEN语句,但我从JDBC [MYOB ODBC]Error getting the literal value of right operand.得到以下[MYOB ODBC]Error getting the literal value of right operand.

实际陈述如下:

 rs = stmt.executeQuery("SELECT sales.InvoiceNumber, sales.ShipToAddress, sales.Date " + "FROM sales, customers " + "WHERE sales.CardRecordID = customers.CardRecordID " + "AND customers.Name = 'Cash Sales' " + "AND sales.Date BETWEEN " + sdate + " AND " + edate + " " + "ORDER BY sales.ShipToAddress ASC, sales.Date DESC" + ";"); 

有人能帮我解决这个问题的正确语法吗? 这是缺少的最后一项function。

编辑: sdateedate当前值分别为25/10/2013,因为它们默认为今天的日期。 我已经设置了我正在测试的虚拟文件,以确保它将提供此日期范围的数据。 另外,对于澄清,我希望搜索日期是包含在内的。

在您的日期周围使用报价:

 rs = stmt.executeQuery("SELECT sales.InvoiceNumber, sales.ShipToAddress, sales.Date " + "FROM sales, customers " + "WHERE sales.CardRecordID = customers.CardRecordID " + "AND customers.Name = 'Cash Sales' " + "AND sales.Date BETWEEN '" + sdate + "' AND '" + edate + "' " + "ORDER BY sales.ShipToAddress ASC, sales.Date DESC" + ";"); 

或者使用预准备语句可能更安全(例如,如果日期来自不受信任的输入):

 SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); java.util.Date startDate = formatter.parse(sdate); java.util.Date endDate = formatter.parse(edate); PreparedStatement pstmt = connection.prepareStatement("SELECT sales.InvoiceNumber, sales.ShipToAddress, sales.Date " + "FROM sales, customers " + "WHERE sales.CardRecordID = customers.CardRecordID " + "AND customers.Name = 'Cash Sales' " + "AND sales.Date BETWEEN ? AND ? " + "ORDER BY sales.ShipToAddress ASC, sales.Date DESC"); pstmt.setDate(1, new java.sql.Date(startDate.getTime())) pstmt.setDate(2, new java.sql.Date(endDate.getTime())) 

between运算符是包含的,但如果您的数据库字段实际上是时间戳,则假定没有时间的日期是00:00:00.000。 因此,在这种情况下,为了使您的日期具有包容性,您可以在结束日期添加一天。 从技术上讲,它还将包括第二天的第一个时刻 (00:00:00.000小时),但根据您的应用,它可能就足够了。

否则你可以在“开始日期”和<在“结束日期再加上一天”上使用>=

 "sales.Date >= '" + sdate + "' AND sales.Date < '" + edatePlusOne + "' " 

看起来您需要以这种格式表达日期:

从’2006-10-01’和’2006-11-30’之间的日期字段中选择*

也看这里 ,不要忘记谷歌是你的朋友! 🙂

 Class.forName("com.mysql.jdbc.Driver"); connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospitall","root",""); PreparedStatement ps=connection.prepareStatement("select * from patient where patientid='"+txtpatientid.getText()+"'"); Statement stm=connection.createStatement(); ResultSet rs=ps.executeQuery(); if(rs.next()){ String patientid=txtpatientid.getText(); String str="select * from patient where patientid='"+patientid+"'"; ResultSet result=stm.executeQuery(str);