设计程序,实现利用提交页面提交要添加的学生信息,然后进入添加处理程序实现添加到数据库。
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<html>
</head><title>添加任意学生的提交页面</title></head>
//insert_stu_2_tijiao.jsp
<body>
<form action="insert_stu_2.jsp" method="post">
<table border="0"width="238"height="252">
<tr><td>学号</td><td><input type="text"name="id"></td></tr>
<tr><td>姓名</td><td><input type="text"name="name"></td></tr>
<tr><td>性别</td><td><input type="text"name="sex"></td></tr>
<tr><td>年龄</td><td><input type="text"name="age"></td></tr>
<tr><td>体重</td><td><input type="text"name="weight"></td></tr>
<tr><td>身高</td><td><input type="text"name="hight"></td></tr>
<tr align="center">
<td colspan="2">
<input type="submit"value="提 交">
<input type="reset"value="取 消 ">
</td>
</tr>
</table>
</form>
</body>
</html>
//insert_stu_2.jsp
<%@ page language="java" import="java.sql.*" pageEncoding="UTF-8"%>
<html>
</head><title>利用PreparedStatement对象添加一条记录页面</title></head>
<body>
<%String driverName="com.mysql.jdbc.Driver";
String userName="root";
String userPwd="184896";
String dbName="students";
String url1="jdbc:mysql://localhost:3306/"+dbName;
String url2="?user="+userName+"&password="+userPwd;
String url3="&userUnicode=true&characterEncoding=UTF-8";
String url=url1+url2+url3;
Class.forName(driverName);
Connection conn=DriverManager.getConnection(url);
String sql="Insert into stu_info(id,name,sex,age,weight,hight)values(?,?,?,?,?,?)";
PreparedStatement pstmt=conn.prepareStatement(sql);
request.setCharacterEncoding("UTF-8");
int id=Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("name");
String sex=request.getParameter("sex");
int age=Integer.parseInt(request.getParameter("age"));
float weight=Float.parseFloat(request.getParameter("weight"));
float hight=Float.parseFloat(request.getParameter("hight"));
pstmt.setInt(1,id);
pstmt.setString(2,name);
pstmt.setString(3,sex);
pstmt.setInt(4,age);
pstmt.setFloat(5,weight);
pstmt.setFloat(6,hight);
int n=pstmt.executeUpdate();
if(n==1){%>数据插入操作成功!<br><%}
else{%>数据插入操作失败!<br><%}
if(pstmt!=null){pstmt.close();}
if(conn!=null){conn.close();}%>
</body>
</html>