代码
嘿嘿,还是承接那个select.jsp
要注意的是,之前的数据库表格默认的主键是id此时要设置id的默认递增,如图:
insert.jsp:
<%--
Created by IntelliJ IDEA.
User: 长风
Date: 2019/9/21
Time: 20:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>数据插入</title>
</head>
<body>
<form action="doinsert.jsp" method="post">
<%--申请插入页面--%>
用户名:<input type="text" name="username" value=""><br>
密 码:<input type="password" name="password" value=""><br>
用户类型:
<select name="type">
<option>管理员</option>
<option>普通用户</option>
</select><br>
<input type="submit" name="" value="注册">
</form>
</body>
</html>
doinsert.jsp:
<%--
<%--
Created by IntelliJ IDEA.
User: 长风
Date: 2019/9/21
Time: 20:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.sql.*" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%!
public static final String DBDRIVER="com.mysql.cj.jdbc.Driver";
public static final String DBURL="jdbc:mysql://localhost:3306/webstore?&useSSL=false&serverTimezone=UTC";
public static final String DBUSER="root";
public static final String DBPASS="123456";
%>
<%!
String username=null;
String password=null;
String type=null;
Connection conn=null;
%>
<%
try{
Class.forName(DBDRIVER);
conn= DriverManager.getConnection(DBURL,DBUSER,DBPASS);
request.setCharacterEncoding("utf-8");
username=request.getParameter("username");
password=request.getParameter("password");
type=request.getParameter("type");
String sql_insert="insert into user_table(用户名, 密码, 用户类型) values ('"+username+"','"+password+"','"+type+"')";
PreparedStatement pst=conn.prepareStatement(sql_insert);
int rs=pst.executeUpdate();
if(rs!=0){
%>
<jsp:forward page="select.jsp"></jsp:forward>
<%
}
}
catch(Exception e){
out.println(e);
}
%>
</body>
</html>
运行结果
插入前:
插入中:
插入后: