jsp數據庫操作之插入

代碼

嘿嘿,還是承接那個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>

運行結果

插入前:
在這裏插入圖片描述
插入中:
在這裏插入圖片描述
插入後:
在這裏插入圖片描述

請點個贊,評個論!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章