我希望为过滤产品创建动态查询。我想要 PRODUCTS 表中的过滤产品 在某些参数的基础上,如
您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行的''附近使用正确的语法
你尝试打印查询:
SELECT * FROM产品WHERE 1 = 1 AND品牌(?,?AND Price<?AND Size<?AND Type =?
Follwing是代码:
public List<Products> Filter_Itemsl(String[] Brand, String[] Flavour, float Price, float Size, String Type) {
List<Object> parameters = new ArrayList<Object>();
ResultSet rs;
List<Products> data = null;
PreparedStatement stmt;
try {
StringBuilder query = new StringBuilder("SELECT * FROM products WHERE 1=1");
if (Brand != null) {
query.append(" AND brand in (");
for (int i = 0; i < Brand.length; i++) {
query.append('?');
if (i < Brand.length - 1) {
query.append(',');
}
parameters.add(Brand[i]);
}
}
if (Flavour != null) {
query.append(" AND Flavour in (");
for (int i = 0; i < Brand.length; i++) {
query.append('?');
if (i < Flavour.length - 1) {
query.append(',');
}
parameters.add(Flavour[i]);
}
}
if (Price != 0) {
query.append(" AND Price < ?");
parameters.add(Price);
}
if (Size != 0) {
query.append(" AND Size < ?");
parameters.add(Size);
}
if (Type != null) {
query.append(" AND Type = ?");
parameters.add(Type);
}
String Query = query.toString();
System.out.println(Query);
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(Query);
int i = 1;
for (Object parameter : parameters) {
stmt.setObject(i++, parameter);
}
rs = stmt.executeQuery();
if (rs != null) {
data = new ArrayList<Products>();
while (rs.next()) {
Products p = new Products();
p.setTitle(rs.getString("Ttile"));
p.setCategory(rs.getString("Category"));
p.setSubCategory(rs.getString("SubCategory"));
p.setSubCategoryTwo(rs.getString("SubCategorytwo"));
p.setPrice(rs.getInt("Price"));
p.setFlavour(rs.getString("Flavour"));
p.setSize(rs.getFloat("Size"));
p.setImage(rs.getString("image"));
p.setBrand(rs.getString("Brand"));
p.setInstock(rs.getString("instock"));
p.setInstockQty(rs.getInt("instockqty"));
p.setType(rs.getString("Type"));
data.add(p);
}
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
System.out.println("----------------------");
System.out.println(e.getMessage());
System.out.println("----------------------");
System.out.println(e.getSuppressed());
System.out.println("----------------------");
e.printStackTrace();
return null;
}
return data;
}
答案 0 :(得分:1)
你错过了每个IN sql语句的结束。
答案 1 :(得分:1)
您需要在for循环后关闭括号
if (Flavour != null) {
query.append(" AND Flavour in (");
for (int i = 0; i < Brand.length; i++) {
query.append('?');
if (i < Flavour.length - 1) {
query.append(',');
}
parameters.add(Flavour[i]);
}
query.append(")");
}