我目前正在编写一个Java Swing应用程序,它从MYOB数据库文件中读取数据并在表格中显示某些信息。我已经能够成功生成所需的SQL语句,但是我无法添加日期之间的搜索功能(我们的数据库非常大,所以我们试图限制结果)。我的一个查询的示例如下(用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)。
我尝试在AND
中使用另一个WHERE
子句并使用BETWEEN
语句,但我从JDBC [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"
+ ";");
是否有人能够帮助我找出正确的语法?这是缺少的最后一项功能。
编辑:sdate
和edate
的当前值分别为25/10/2013,因为它们默认为今天的日期。我已经设置了我正在测试的虚拟文件,以确保它将提供此日期范围的数据。另外,对于澄清,我希望搜索日期是包含在内的。
答案 0 :(得分:10)
在日期周围使用引号:
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 + "' "
答案 1 :(得分:0)
答案 2 :(得分:-1)
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);