2013-02-15 57 views
-1

當我做兩個日期之間一個月(間02-02-201309-02-2013例如) 搜索結果之間的SQL數據是從03-01-201308-01-201303-02-201308-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 < '" + datetosearch.getText().toString()+"' "; 
    } 

    if (datesearch.getText().trim().length()>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()<11) { 
     StrQr=StrQr + " and type like '%" + typesearch.getSelectedItem().toString() + "%' "; 
    } 

    if (usersearch.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(); 
} 

回答

0

如果我猜的話,我會說這是在這裏:

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注入。改爲使用參數化查詢。

+0

我試過使用> =和<=但不工作顯示相同的結果數據庫中的日期格式是SS-MM-YYYY HH:MM:SS – user2011577 2013-02-15 23:09:39

+0

@ user2011577 - 什麼是SS--不熟悉的 - 你沒有在日期時間字段中存儲日期? – sgeddes 2013-02-15 23:56:33

+0

ss意味着秒我保存日期時間在數據庫列數據類型爲VARCHAR(45)當我嘗試將其更改爲數據類型DATETIME它給出的錯誤爲:在有效值 – user2011577 2013-02-16 00:03:03