Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the PrepareStatement not generate correct SQL query?

Tags:

java

sql

mysql

jdbc

Below is my PrepareStatement code. It does not generate correct SQL-query. Also it does not come beyond 1st println-statement. Also it says ** NOT SPECIFIED ** in the query (please see below).

How can we fix this, please?

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

output:

ps1 Before : com.mysql.jdbc.JDBC4PreparedStatement@14d55de: select stuId, name, relationsName, 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

It does not come beyond this point. Also it says NOT SPECIFIED in the query (please see to the end).

Any insights please?

       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();
like image 800
Zafar Avatar asked Sep 11 '26 22:09

Zafar


1 Answers

because the placeholders where enclosed with single quotes, thus making it a value an not a parameter anymore. you should get rid of it, eg

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

for LIKE statement, you should concatenate the value in java, not in sql,

ps1.setString(1, stuId + '%');
like image 147
John Woo Avatar answered Sep 14 '26 12:09

John Woo