通过使用 update 语句,去更新表中的数据。同时学会如何给页面 input 标签传值。
数据库的数据修改时,使用update 语句,语法如下:
update 表名 set 字段1=值1,字段2=值2,字段3=值3 where 字段1=字段1值
update 表名 set 字段1=值1,字段2=值2,字段3=值3 where 字段1=字段1值
上节课学了查询语法,我们查询留言数据如下图所示:
划出来这个 null 在数据库中代表没有任何值。
下面我们学习使用 update 把 author 赋值为李白,那更新脚本为:
update liuyanban set author = '李白' where id = 16;
执行脚本后,我们查询数据,看有没有变化,查询结果如下图所示: /**
* 根据id 获取留言板数据
* @param id
* @return
*/
public Liuyanban selectLiuyanbanById(String id);
/**
* 更新留言数据
* @param model
* @return
*/
public int updateLiuyanban(Liuyanban model);
<select id="selectLiuyanbanById" resultType="cn.qcwl.model.Liuyanban">
select id,title,content,author,add_time from liuyanban
where id=#{id}
</select>
<update id="updateLiuyanban" >
update liuyanban
set title=#{title},content=#{content},author=#{author}
where id=#{id}
</update>
注意,一定要写 where 条件,否则会更新所有的数据。有了前面的更新数据了,那controller 中修改有一个方法进行接收要修改的数据。
需要添加一个方法,接收留言的 id 值,具体如下图所示:
@RequestMapping("editLiuyan")
public String editLiuyan(Model model,int id) {
Liuyanban liuyanbanModel =liuyanbanMapper.selectLiuyanbanById(id);
if (liuyanbanModel!=null) {
model.addAttribute("liuyan", liuyanbanModel);
}else {
model.addAttribute("error", "无效的id值");
}
List<Liuyanban> liuyanList = liuyanbanMapper.selectLiuyanban();
model.addAttribute("liuyanList", liuyanList);
return "index";
}
<form action="/saveLiuyan" method="post">
<div class="form-group">
<label for="ly_title">标题</label>
<input type="text" class="form-control" id="ly_title"
name="ly_title" placeholder="标题" value="${liuyan.title }">
</div>
<div class="form-group">
<label for="ly_content">内容</label>
<input type="text" class="form-control" id="ly_content"
name="ly_content" placeholder="内容" value="${liuyan.content }">
</div>
<div class="form-group">
<label for="ly_author">留言人</label>
<input type="text" class="form-control" id="ly_author"
name="ly_author" placeholder="留言人" value="${liuyan.author }">
</div>
<div>
<label class="label label-warning ">${error}</label>
</div>
<div>
<input type="hidden" name="id" value="${liuyan.id }" >
<button class="button">提交留言 </button>
</div>
</form>
在列表中添加了一个操作列,同时内容显示中也添加了一个 a 超链接标签。
注意看 href 这个属性,这里调用 editLiuyan同时给传了一个 id 的值。在地址和值之间用的是?号进行的分隔。
@RequestMapping("saveLiuyan")
public void saveLiuyan(Model model,String ly_title,String ly_content,String ly_author,
Integer id, // 新添加一个 id 属性
HttpServletRequest request,HttpServletResponse response) throws IOException {
Liuyanban liuyanbanModel = new Liuyanban();
liuyanbanModel.setTitle(ly_title);
liuyanbanModel.setContent(ly_content);
liuyanbanModel.setAuthor(ly_author);
if (id==null) {
liuyanbanMapper.insertLiuyanban(liuyanbanModel);
}else {
liuyanbanModel.setId(id);
liuyanbanMapper.updateLiuyanban(liuyanbanModel);
}
response.sendRedirect("/");
}