I've got this query:
SELECT * FROM Subject
with this WHERE clause :
WHERE Tag like '%something%'
This query works fine with SQL Manager, but JDBC keeps crashing with this exception:
Incorrect syntax near the keyword 'WHERE'.
The code is:
String query = "SELECT * FROM Subject";
if (tags != null && tags.length>0) {
for(int i = 0;i<tags.length;i++){
query = query + " WHERE Tag like '%" + tags[i] + "%'";
}
}
and so on.
Why is this incorrect?
Of course it will crash because the final query is not correct, consider you have this piece of information :
String tags[] = {"aa", "bb", "cc"};
String query = "SELECT * FROM Subject";
for (int i = 0; i < tags.length; i++) {
query = query + " WHERE Tag like '%" + tags[i] + "%'";
}
System.out.println(query);
This should return :
SELECT * FROM Subject WHERE Tag like '%aa%' WHERE Tag like '%bb%' WHERE Tag like '%cc%'
//---------------------^^--------------------^^--------------------^^
And this not correct Syntax.
To avoid this problem you have to use :
String query = "SELECT * FROM Subject WHERE ";
String or = "";
for (int i = 0; i < tags.length; i++) {
query += or +" Tag like '%" + tags[i] + "%'";
or = " OR ";
}
This can show you :
SELECT * FROM Subject WHERE Tag like '%aa%' OR Tag like '%bb%' OR Tag like '%cc%'
Note
This still not perfect, to avoid any syntax error or SQL Injection i suggest to use PreparedStatement, for example :
for (int i = 0; i < tags.length; i++) {
//query += or + " Tag like '%" + tags[i] + "%'";
query += or + " Tag like ?";
or = " OR ";
}
//query = SELECT * FROM Subject WHERE Tag like ? OR Tag like ? OR Tag like ?
Connection connection = null;
try (PreparedStatement stm = connection.prepareStatement(query)) {
for (int i = 1; i <= tags.length; i++) {
stm.setString(i, "%" + tags[i-1] + "%");//set values to your query
}
ResultSet rs = stm.executeQuery();//execute your query
while(rs.next()){
//get your results
}
}
You are looping over the "WHERE". Adding it with each new tag.
String[] tags = new String[2];
tags[0] = "bob";
tags[1] = "hank";
String query = "SELECT * FROM Subject";
if (tags != null && tags.length>0) {
for(int i = 0;i<tags.length;i++){
query = query + " WHERE Tag like '%" + tags[i] + "%'";
}
}
System.out.println(query);
This will return
SELECT * FROM Subject WHERE Tag like '%bob%' WHERE Tag like '%hank%'
String query = "SELECT * FROM Subject";
if (tags != null && tags.length > 0) {
query += " WHERE "; // do this once
for(int i = 0;i < tags.length; i++){
query += " Tag like '%" + tags[i] + "%'";
query += " OR ";
}
query = query.substring(0, query.lenght() - 3); // Remove last "OR"
}
Found out the problem. I didn't reset the query at the start of each loop's round. In fact it added a WHERE clause each time. Now it works fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.