为什么PrepareStatement不能生成正确的SQL查询?

时间:2013-01-11 14:16:09

标签: java mysql sql jdbc

以下是我的PrepareStatement代码。它不会生成正确的SQL查询。 它也没有超越1st println-statement。另外它在查询中说**未指明**(请参见下文)。

我们怎么解决这个问题呢?

   ps1 = con.prepareStatement(
                     "select stuId, name, relationsName, houseAddress, houseNumber from temp where "
                        + " stuId like '?%' and " 
                        + " sex = '?' and " 
                        + " name like '?%' and "
                        + " age BETWEEN ? and ? and "
                        + " relationsName like '?%' " 
                        + " order by name asc limit 0, 150000 "
               );

               System.out.println("ps1 Before : " + ps1);

输出:

  

ps1之前:com.mysql.jdbc.JDBC4PreparedStatement@14d55de:选择   stuId,name,relationsName,houseAddress,houseNumber from temp where   stuId喜欢'?%'和sex ='?'并命名为'?%'和年龄BETWEEN **   未指明**和**未指定**和relationsName喜欢'?%'   按名称排序asc limit 0,150000

它没有超出这一点。此外,它在查询中显示 NOT SPECIFIED (请参见结尾)。

有什么见解吗?

       ps1.setString(1, stuId);
       ps1.setString(2, gender);
       ps1.setString(3, name);
       ps1.setInt(4, startAge);
       ps1.setInt(5, endAge);
       ps1.setString(6, relationsName);

       System.out.println("ps1 After : " + ps1);

       rs = ps1.executeQuery();

1 个答案:

答案 0 :(得分:11)

因为占位符用单引号括起来,因此使它成为一个值而不再是一个参数。你应该摆脱它,例如

ps1 = con.prepareStatement(
                 "select stuId, name, relationsName, houseAddress, houseNumber from temp where "
                    + " stuId like ? and " 
                    + " sex = ? and " 
                    + " name like ? and "
                    + " age BETWEEN ? and ? and "
                    + " relationsName like ? " 
                    + " order by name asc limit 0, 150000 "
           );

对于LIKE语句,你应该连接java中的值,而不是sql,

ps1.setString(1, stuId + '%');