为了账号安全,请及时绑定邮箱和手机立即绑定

sql拼接

我的参数没乱码,sql却成了select ID,COMMAND,DESCRIPTION,CONTENT from message where 1=1 and COMMAND = ?   select ID,COMMAND,DESCRIPTION,CONTENT from message where 1=1 and DESCRIPTION like '%' ? '%' 参数就没替换上去,这是为什么?那位大神能帮我解决一下

正在回答

2 回答

req.setCharacterEncoding("utf-8");

try {

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 connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/micro_message", "root", "root");

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 = (PreparedStatement) connection.prepareStatement(sql.toString());

System.out.println(paramList.size());

for (int i = 0; i < paramList.size(); i++) {

statement.setString(i+1, paramList.get(i));//sql语句中出现的?是从第一个开始数

}

System.out.println(sql.toString());

ResultSet resultSet = statement.executeQuery();

List<Message> messageList = new ArrayList<Message>();

while(resultSet.next()){

Message message = new Message();

messageList.add(message);

message.setId(resultSet.getString("ID"));

//System.out.println(resultSet.getString("ID"));

message.setCommand(resultSet.getString("COMMAND"));

message.setDescription(resultSet.getString("DESCRIPTION"));

message.setContent(resultSet.getString("CONTENT"));

}

req.setAttribute("messageList", messageList);


0 回复 有任何疑惑可以回复我~

把代码贴出来

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
通过自动回复机器人学Mybatis---基础版
  • 参与学习       107417    人
  • 解答问题       786    个

微信公众号自动回复功能学习Mybatis,基础教程加案例实战方式学习

进入课程
意见反馈 帮助中心 APP下载
官方微信