[英]how can i improve the search using date in sql database in java
I made a software using the java language and MS SQL Server as the database. 我使用Java语言和MS SQL Server作为数据库制作了一个软件。 The problem am facing is that when I search for a date range using two dates, it's giving items which I have not requested. 面临的问题是,当我使用两个日期搜索日期范围时,它给出的是我未请求的项目。
For example, if I need items from 1st to 7th October, it includes items on the 11th, 12th, 13th, 14th, 15th, 16th, etc. 例如,如果我需要10月1日至7月7日的物品,则其中包括11日,12日,13日,14日,15日,16日等的物品。
the date format am using MMM d,yyyy 日期格式使用MMM d,yyyy
I have used the following code 我使用了以下代码
String val1 = ((JTextField)jdate1.getDateEditor().getUiComponent()).getText();
String val2 = ((JTextField)jdate2.getDateEditor().getUiComponent()).getText();
String sql = " select * from Report_details where Date between '"+val1+"' and '"+val2+"' ";
// conn is some Connection
PreparedStatement myStmt = conn.prepareStatement(sql);
ResultSet rs = myStmt.executeQuery();
if(rs.next()){
// do stuff
}
Do not trust user input. 不信任用户输入。
String sql = "select * from Report_details where Date between ? and ?";
....
Date dt1 = new SimpleDateFormat("MMM d,yyyy").parse(val1);
// better yet, have your date picker return a Date object
....
myStmt.setDate(1, dt1);
....
should be the way to go (or setTime or setTimestamp, depending on your table definition) 应该是方法(或setTime或setTimestamp,取决于您的表定义)
NB: do not copy paste this, just a hint to get you off in the right direction. 注意:请勿复制粘贴此内容,仅是使您朝正确方向前进的提示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.