基于java中查询参数值的动态查询

时间:2017-11-17 04:17:04

标签: java

我想根据查询参数的值编写动态查询。我有像这样的字符串查询

String strSQL = "select tb_r_orderdata.customerid,\n" +
                            "REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','') as paydate,\n" +
                            "tb_r_orderdata.amount,\n" +
                            "tb_r_orderdata.acquirementid,\n" +
                            "tb_r_orderdata.tracking_ref,\n" +
                            "tb_m_biller_product.billerdesc, \n" +
                            "tb_m_biller_product.productdesc, \n" +
                            "tb_r_orderdata.hpno, \n" +
                            "tb_r_orderdata.email, \n" +
                            "tb_r_orderdata.rc, \n" +
                            "tb_r_orderdata.rcdesc, \n" +
                            "tb_r_orderdata.additionaldata_pay \n" +
                            "from tb_r_orderdata JOIN tb_m_biller_product ON tb_r_orderdata.productid=tb_m_biller_product.productid AND tb_r_orderdata.billerid=tb_m_biller_product.billerid \n" +
                            "where status='SUCCESS';"; 

这样的结果,如果查询参数中有值或不存在,则根据条件添加字符串查询。

这是我的条件

String newstrSQL = strSQL;
PreparedStatement pst=null;

if (period != null) {
   newstrSQL = strSQL + "and REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','')>=?";
}

if (tanggal != null) {
    newstrSQL = strSQL + "and REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','')<=?";
}

if (billerid != null) {
    newstrSQL = strSQL + "and tb_m_biller_product.billerid  = ?";
}

if (productid != null) {
    newstrSQL = strSQL + "and tb_m_biller_product.productid  = ?";
}

if (custom != null) {
    newstrSQL = strSQL + "and" + searchby + " = ?";
}

pst = con.prepareStatement(newstrSQL);
pst.setString(1, period);
pst.setString(2, tanggal);
pst.setString(3, billerid);
pst.setString(4, productid);
pst.setString(5, custom);

rs = pst.executeQuery();

我测试了它,但结果总是为零,并且没有语法错误。谢谢,抱歉英文不好

1 个答案:

答案 0 :(得分:0)

您已在字符串where status='SUCCESS';中添加了分号,这意味着您的查询将在此处结束,并且您在此处追加的剩余内容将不会像您在此处strSQL + "and REPLACE(REPLACE(REPLACE(LEFT(finishtime,10),'-',''),':',''),'T','')>=?";那样执行。

不要用分号结束strSql并尝试。