首先写一个sql语句,
private String insert = “INSERT INTO usertype(user_type,rank) VALUES(?,?)”;
然后传入数据,判断传入的数据不为空
第二步,获取到页面传过来的参数,
private void doInsert(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userType = request.getParameter(“userType”);
String rank = request.getParameter(“rank”);
因为原本获取出来的中文数据是乱码的,然后用定义好的工具类转换一下格式。
userType = Tools.ISOtoUTF8(userType);
rank = Tools.ISOtoUTF8(rank);
System.out.println(userType + " " + rank);
用已经定义好的工具类:isNotnull判断数据是否为空
if (Tools.isNotNull(userType) && Tools.isNotNull(rank)) {
UserType uType = new UserType();
uType.setUserType(userType);
uType.setRank(rank);
声明一个Boolean类型的变量,调用insert方法,如果新增成功, bolS为true,失败为false。
boolean bolS = userTypeService.insert(uType);
if (bolS) {
request.setAttribute(“msg”, “新增成功”);
} else {
request.setAttribute(“msg”, “新增失败”);
}
System.out.println(“bbbbb”);
request.setAttribute(“toUrl”, “/UserTypeServlet?fun=list”);
} else {
request.setAttribute(“msg”, “请填写完整”);
request.setAttribute(“toUrl”, “/UserTypeServlet?fun=insert”);
}
然后转发到一个消息页面,显示出是否新增成功的信息。 request.getRequestDispatcher("/jsp/message.jsp").forward(request, response);
}
用servelt接收页面传过来的的数据传到数据库,然后调用已经封装好的连接数据库的一个工具类保存数据。如果不捕获异常的话可以用throws SQLException把异常抛出。最后用finally就是为了无论是否发生异常都关闭数据库接口。
public boolean insert(UserType t) {
boolean bolR = false;
try {
conn = DbUtil.getConnection();
ps = conn.prepareStatement(insert);
ps.setString(1, t.getUserType());
ps.setString(2, t.getRank());
bolR = ps.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtil.close(conn, ps, rs);
}
return bolR;
}
以上是我对新增的一点点理解,因为才刚学不久理解不是很透彻,可能会有错误。如果我理解错了请评论或者私信我都行