public List<Product> findByIddd(String guess) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Product> products = new ArrayList<>(); try { conn = DBHelper.getConnection(); String sql = "select productid, category, cname, ename, image, " + "listprice, unitcost, descn " + "from products where productid = ? "; pstmt = conn.prepareStatement(sql); pstmt.setString(1, guess); rs = pstmt.executeQuery(); while (rs.next()) { Product p = new Product(); p.setProductid(rs.getString("productid")); p.setCategory(rs.getString("category")); p.setCname(rs.getString("cname")); p.setEname(rs.getString("ename")); p.setImage(rs.getString("image")); p.setListprice(rs.getDouble("listprice")); p.setUnitcost(rs.getDouble("unitcost")); p.setDescn(rs.getString("descn")); products.add(p); } } catch (SQLException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } return products; }改成返回输出所有包含guess关键字的数据要怎么改
时间: 2024-01-16 17:02:21 浏览: 158
要查询所有包含 `guess` 关键字的数据,可以将 SQL 语句中的 `where` 子句改为使用 `like` 操作符进行模糊匹配。具体的改动如下所示:
```
public List<Product> findByIddd(String guess) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Product> products = new ArrayList<>();
try {
conn = DBHelper.getConnection();
String sql = "select productid, category, cname, ename, image, " +
"listprice, unitcost, descn " +
"from products " +
"where cname like ? or ename like ?"; // 改动的语句
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "%" + guess + "%"); // 模糊匹配
pstmt.setString(2, "%" + guess + "%"); // 模糊匹配
rs = pstmt.executeQuery();
while (rs.next()) {
Product p = new Product();
p.setProductid(rs.getString("productid"));
p.setCategory(rs.getString("category"));
p.setCname(rs.getString("cname"));
p.setEname(rs.getString("ename"));
p.setImage(rs.getString("image"));
p.setListprice(rs.getDouble("listprice"));
p.setUnitcost(rs.getDouble("unitcost"));
p.setDescn(rs.getString("descn"));
products.add(p);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
return products;
}
```
这样修改后,该方法会查询出所有包含 `guess` 关键字的数据,无论是在 `cname` 列还是在 `ename` 列中出现的。
阅读全文