public List<Course> search(String name, String teacher, String classroom) { String sql = "select * from course where "; if (name != "") { sql += "name like '%" + name + "%'"; } if (teacher != "") { sql += "teacher like '%" + teacher + "%'"; } if (classroom != "") { sql += "classroom like '%" + classroom + "%'"; } List<Course> list = new ArrayList<>(); Connection conn = DBUtil.getConn(); Statement state = null; ResultSet rs = null; try { state = conn.createStatement(); rs = state.executeQuery(sql); Course bean = null; while (rs.next()) { int id = rs.getInt("id"); String name2 = rs.getString("name"); String teacher2 = rs.getString("teacher"); String classroom2 = rs.getString("classroom"); bean = new Course(id, name2, teacher2, classroom2); list.add(bean); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(rs, state, conn); } return list; }
时间: 2024-04-01 08:33:35 浏览: 68
多表连接查询综合运用-select查询
这段代码是一个搜索课程的方法,根据传入的课程名称、教师、教室信息来查询符合条件的课程记录。方法中使用了SQL语句拼接的方式生成动态查询语句,根据传入的参数来拼接不同的查询条件。最后将查询结果封装成Course对象的集合返回。需要注意的是该代码存在SQL注入的风险,建议使用PreparedStatement来进行参数化查询,避免SQL注入攻击。
阅读全文