我收到了这个问题:
SELECT * FROM Subject
使用此WHERE子句:
WHERE Tag like '%something%'
此查询适用于SQL Manager,但JDBC会因此异常而崩溃:
Incorrect syntax near the keyword 'WHERE'.
代码是:
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] + "%'";
}
}
等等。
为什么这不正确?
答案 0 :(得分:4)
当然它会崩溃,因为最终查询不正确,请考虑您有这条信息:
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);
这应该返回:
SELECT * FROM Subject WHERE Tag like '%aa%' WHERE Tag like '%bb%' WHERE Tag like '%cc%'
//---------------------^^--------------------^^--------------------^^
这不正确的语法。
要避免此问题,您必须使用:
String query = "SELECT * FROM Subject WHERE ";
String or = "";
for (int i = 0; i < tags.length; i++) {
query += or +" Tag like '%" + tags[i] + "%'";
or = " OR ";
}
这可以告诉你:
SELECT * FROM Subject WHERE Tag like '%aa%' OR Tag like '%bb%' OR Tag like '%cc%'
注意强>
这仍然不完美,以避免任何语法错误或SQL注入我建议使用PreparedStatement,例如:
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
}
}
答案 1 :(得分:1)
你正在循环#34; WHERE&#34;。添加每个新标签。
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);
这将返回
SELECT * FROM Subject WHERE Tag like '%bob%' WHERE Tag like '%hank%'
答案 2 :(得分:0)
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"
}
答案 3 :(得分:0)
发现问题所在。 我没有在每个循环的回合开始时重置查询。 实际上每次都添加了一个WHERE子句。 现在它工作正常。