q跪求大神看Bug在哪里
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
//设置字符编码
req.setCharacterEncoding("UTF-8");
//接收页面的值
String command =req.getParameter("command");
String description =req.getParameter("description");
//向页面传值
req.setAttribute("command", command);
req.setAttribute("description", description);
//加载驱动。连接数据库
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/message","root","123123");
//操作数据库并声明,用where1=1进行拼装sql语言
StringBuilder sql =new StringBuilder( "select ID ,COMMAND,DESCRIPTION,CONTENT from MESSAGE where 1=1");
//定义一个集合来暂缓拼接,先拼接好才用到声明里
List <String> paramList=new ArrayList<String>();
//判断一个接收的值是不是为空,不为空才拼接
if(command != null && !"".equals(command.trim())) {
sql.append(" and COMMAND=?");
paramList.add(command);
}
if(description != null && !"".equals(description.trim())) {
sql.append(" and DESCRIPTION like '%' ? '%'");
paramList.add(description);
}
//进行声明
PreparedStatement statement= conn.prepareStatement(sql.toString());
//将拼接好后的sql语言放到集合中
for(int i = 0; i < paramList.size(); i++) {
statement.setString(i + 1, paramList.get(i));
}
//查询数据库
ResultSet rs = statement.executeQuery();
//查询结果放在一个集合中
List<Message> messageList = new ArrayList<Message>();
while(rs.next()) {
System.out.println(messageList);
Message message = new Message();
messageList.add(message);
message.setId(rs.getInt("ID"));;
message.setCommand(rs.getString("COMMAND"));
message.setDescription(rs.getString("DESCRIPTION"));
message.setContent(rs.getString("CONTENT"));
}
//向页面传值
req.setAttribute("messageList",messageList);