jsp数据库基础之--往MySQL数据库添加数据
项目地址:https://gitee.com/martinHuang/jsp-basic/
前面讲到了查询,还讲到了从表单获取数据,这些是最最基本的了。下面来说说往MySQL数据库添加数据。先讲怎么做,后面再说明原理
1、新建一个jsp文档,名为insert.jsp,放到fromAction文件夹下
2、在insert.jsp文档中,添加如下内容
<%@page import="jdk.nashorn.internal.ir.RuntimeNode.Request"%> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="com.Database.*"%> <%@ page import="java.sql.*"%> <% request.setCharacterEncoding("utf-8"); String name = request.getParameter("name"); String pro = request.getParameter("pro"); String sql = "insert into personinfo(name , birthProvince) values("+name+","+pro+")"; conDB db = new conDB(); db.connectDB(); Statement state = db.getConnection().createStatement(); int flag = state.executeUpdate(sql); if(flag != 0) { out.println("<script>alert(插入成功!);history.go(-1);</script>"); } else { out.println("<script>alert(插入失败!);history.go(-1);</script>"); } state.close(); %>
3、在WebContent文件夹下新建insertData.html,添加如下内容
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>通过表单插入数据</title> </head> <body> <form action="FormAction/insert.jsp" method="post"> <input type="text" name="name" placeholder="请输入姓名"> <input type="text" name="pro" placeholder="请输入出生地"> <input type="submit" value="提交"> </form> </body> </html
4、测试运行
点击提交
数据库插入前:
插入后:
下面来解释一下关键部分(insert.jsp)
1、 request.setCharacterEncoding("utf-8");保证从表单传递过来的数据不乱码,utf-8是我insertData.html的页面编码
2、request.getParameter("name");根据表单元素name的属性值返回内容,为字符串String型
3、state.executeUpdate(sql);对于executeUpdate()查询java API文档
这个方法可以用来执行Insert Update Delete语句,我们现在使用的都为DML语言,即执行之后回操作行数,如果不为0的话,说明操作成功,否则失败