在两个日期之间搜索My SQL中的数据

当我在一个月内的两个日期之间进行搜索时(例如,在09-02-2013 2月2 02-02-201309-02-2013 2月9日之间),结果显示从09-02-2013月1日至09-02-2013月1日以及09-02-2013 2月3 02-02-201309-02-2013 08-02-2013

以下是我的代码:

 try { dconfig dcf=new dconfig(); java.sql.Connection connection; Class.forName(dcf.driver); connection=(com.mysql.jdbc.Connection) DriverManager.getConnection(dcf.StrUrl,dcf.StrUid,dcf.StrPwd); ResultSet rs = null; ResultSet rscount; String StrQr=""; if (jobnamesearch.getText().trim().length()>0 ) { StrQr=StrQr + " and job_name like '%" + jobnamesearch.getText().trim() +"%' "; } if (datetosearch.getText().trim().length()>0) { StrQr=StrQr + " and date > '" + datesearch.getText().toString()+"' "; StrQr=StrQr + " and date 0 && datetosearch.getText().trim().length()==0) { StrQr=StrQr + " and date like '%" + datesearch.getText().trim().toString()+ "%' "; } if (dwsearch.getText().trim().length()>0 ) { StrQr=StrQr + " and dw_no like '%" + dwsearch.getText().trim() + "%' "; } if (remsearch.getText().trim().length()>0 ) { StrQr=StrQr + " and rem_no like '%" + remsearch.getText().trim() + "%' "; } if (typesearch.getSelectedItem().toString().length()0) { StrQr=StrQr + " and user like '%" + usersearch.getSelectedItem().toString() + "%' "; } java.sql.PreparedStatement stmt=connection.prepareStatement("SELECT ID,job_name,details,type,dw_no,rem_no,user,date FROM tracker where 1=1 " + StrQr +" order by ID DESC"); java.sql.PreparedStatement stmtcount=connection.prepareStatement("SELECT Count(*) FROM tracker where 1=1 " + StrQr +""); rs = stmt.executeQuery(); rscount = stmtcount.executeQuery(); } 

如果我不得不猜测,我会说它在这里:

 if (datetosearch.getText().trim().length()>0) { StrQr=StrQr + " and date > '" + datesearch.getText().toString()+"' "; StrQr=StrQr + " and date < '" + datetosearch.getText().toString()+"' "; } 

你说日期> - 尝试将其改为> =和<=。

 if (datetosearch.getText().trim().length()>0) { StrQr=StrQr + " and date >= '" + datesearch.getText().toString()+"' "; StrQr=StrQr + " and date <= '" + datetosearch.getText().toString()+"' "; } 

此外,如果您的数据库中的日期是日期时间,那么<=也将无效。 您需要添加一天或附加23:59,因为它将在午夜搜索。

希望这可以帮助。

顺便说一句 - 这非常容易受到SQL注入攻击。 请查看使用参数化查询。