简体   繁体   中英

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. 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.

the date format am using 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)

NB: do not copy paste this, just a hint to get you off in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM