略坑
2016-07-27 00:22
select ID,COMMAND,DESCRIPTION,CONTENT from message where 1=1
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'COMMAND ='??????'' at line 1
这是我的查询语句,以及错误报告,求指教
这个是传入到数据库的时候没有对数据进行编码,数据库读不到数据,jdbc:mysql://127.0.0.1:3306/micro_message?characterEncoding=utf8","root","root"
是空格的问题, sql.append(" and COMMAND =?");
在and 的前面加一个空格。
package com.imooc.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.imooc.bean.Message;
/*
*列表页面初始化控制
*/
@SuppressWarnings("serial")
public class ListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
req.setCharacterEncoding("UTF-8");
String command=req.getParameter("command");
String description=req.getParameter("description");
Class.forName("com.mysql.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/micro_message","root","admin");
StringBuilder sql=new StringBuilder();
sql.append("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 =?");
paramlist.add(description);
}
PreparedStatement stat=conn.prepareStatement(sql.toString());
for (int i=0;i<paramlist.size();i++) {
stat.setString(i+1, paramlist.get(i));
}
ResultSet rs=stat.executeQuery();
List <Message> messagelist=new ArrayList<Message>();
System.out.println(sql);
while(rs.next()){
Message message=new Message();
message.setId(rs.getString("ID"));
message.setCommand(rs.getString("COMMAND"));
message.setDescription(rs.getString("DESCRIPTION"));;
message.setContent(rs.getString("CONTENT"));
messagelist.add(message);
}
req.setAttribute("messagelist", messagelist);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req, res);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, res);
}
}
通过自动回复机器人学Mybatis---基础版
107412 学习 · 786 问题
相似问题