慕用9049269
2016-08-18 20:30
List<Message> messageList = new ArrayList<Message>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection;
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/micro_message","root","root");
StringBuilder sql = new StringBuilder("select id,command,desription,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(desription != null && !"".equals(desription.trim())){
sql.append("and desription like '%' ? '%' ");
paramList.add(desription);
}
PreparedStatement statement = connection.prepareStatement(sql.toString());
for(int i=0;i<paramList.size();i++){
statement.setString(i + 1,paramList.get(i));
}
ResultSet rs = statement.executeQuery();
Message message = new Message();
while(rs.next()){
message.setId(rs.getString("id"));
message.setCommand(rs.getString("command"));
message.setDesription(rs.getString("desription"));
message.setContent(rs.getString("content"));
messageList.add(message);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return messageList;
Message message = null;
while(rs.next()){
message = new Message();
message.setId(rs.getString("id"));
message.setCommand(rs.getString("command"));
message.setDesription(rs.getString("desription"));
message.setContent(rs.getString("content"));
messageList.add(message);
}
每次循环都要新声明一个对象,你那样写其实就只声明了一个message 对象。
谢谢楼上的答案,我纠结了几天了,真是豁然开朗啊
这个初学者经常碰到,我以前也是,一般把新生成的对象放到循环里就ok了!
通过自动回复机器人学Mybatis---基础版
107412 学习 · 786 问题
相似问题