2

下面是我的 PrepareStatement 代码。它不会生成正确的 SQL 查询。它也没有超出第一个 println 语句。它还在查询中显示** NOT SPECIFIED **(请参见下文)。

请问我们如何解决这个问题?

   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、relationshipName、houseAddress、houseNumber from temp where stuId like '?%' and sex = '?' and name like '?%' and age BETWEEN ** NOT SPECIFIED ** and ** NOT SPECIFIED ** and relationsName like '?%' order by name asc limit 0, 150000

它并没有超出这一点。它还在查询中表示指定(请参阅最后)。

请问有什么见解吗?

       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();
4

1 回答 1

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 "
           );

forLIKE语句,你应该在java中连接值,而不是在sql中,

ps1.setString(1, stuId + '%');
于 2013-01-11T14:17:17.807 回答