如果在运行时查询中为NULL,则如何设置参数值

时间:2013-12-05 13:07:57

标签: mysql sql

我想根据以下条件获取记录

String sql="select *from employee where email like "+student.email+" OR phoneno="+student.pno;

有时,电子邮件或电话,仅限电子邮件,电话可能只有空值,在这种情况下,如果电子邮件和电话为空,它将显示所有记录。如果电子邮件只为null,那么它将显示基于电话的记录,不是这样的。

请问好吗?

2 个答案:

答案 0 :(得分:1)

您可以使用IF

String sql="SELECT *
FROM employee
WHERE IF("+student.email+" IS NULL, 1, email = "+student.email+") OR
      IF("+student.pno+" IS NULL, 1, phoneno = "+student.pno+")";

我建议使用绑定器,而不是直接使用SQL,因为它容易进行SQL注入,而且整体上更安全,没有引起问题的时髦字符。

答案 1 :(得分:0)

i tired with following code. now i am getting expected output exactly. any one 
can tell me another way . 

StringBuilder sql=new StringBuilder("select *from aerp_marketing");
        int i=0,k=0;
    if(!(pno.equals(null)||pno.equals("")))
        {
            i=1;k=1;
        sql.append(" mobileno like '"+pno+"'");
        }
        if(!(email.equals(null)||email.equals("")))
    {
         i=1;
     if(k==0){
           k=1;
           sql.append(" email like '"+email+"'");
     }else{
        k=1;
        sql.append("and email like '"+email+"'");
      }
      }
          if(!(doentered.equals(null)||doentered.equals("")))
    {
           i=1;
        if(k==0){
        k=1;
        sql.append(" doentered = '"+doentered+"'");
        }else{
        k=1;
        sql.append("and doentered = '"+doentered+"'");
            }
    }
           if(!(yostudy.equals(null)||yostudy.equals("")))
    {
        i=1;
        if(k==0){
        k=1;
        sql.append(" yostudy like '"+yostudy+"'");
        }else{
        k=1;
        sql.append("and yostudy like '"+yostudy+"'");
            }
    }
            if(!(college.equals(null)||college.equals("")))
    {
        i=1;
        if(k==0){
        k=1;
        sql.append(" college like '"+college+"'");
             }else{
        k=1;
        sql.append("and college like '"+college+"'");
        }
    }

    if(i==1)
            {
                sql.insert(27, " where ");
    }

              String sqlquery=sql.toString();

    now query is ready to execute........