编写程序,实现对数据库StudentInfo中的表student进行插入操作.要求使用预处理语句对象PreparedStatement完成以下数据的插入: insert into student values('001','张三',18,'女') 注:给定数据库登录用户名:sa,密码:123. Input.jsp: 请输入待新增的学生信息 学号: 姓名: 年龄: 性别: addStudent.jsp: <% String url="jdbc:sqlserver://localhost;databaseName=StudentInfo"; request.setCharacterEncoding("utf-8"); String sno = request.getParameter("sno"); String sname = request.getParameter("sname"); int sage = Integer.valueOf(request.getParameter("sage")); String sex = request.getParameter("sex"); try{ //补全此部分代码 } // 捕获异常 catch(SQLException ex) { System.out.println ("\n*** 发生SQL异常 ***\n"+ex.getMessage()); } catch(ClassNotFoundException ex) { System.out.println(ex); }
时间: 2024-01-21 21:16:23 浏览: 126
用JDBC向Students表中插入数据
addStudent.jsp:
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Student</title>
</head>
<body>
<h1>Add Student</h1>
<form action="insertStudent.jsp" method="post">
<label for="sno">学号:</label>
<input type="text" id="sno" name="sno" /><br>
<label for="sname">姓名:</label>
<input type="text" id="sname" name="sname" /><br>
<label for="sage">年龄:</label>
<input type="text" id="sage" name="sage" /><br>
<label for="sex">性别:</label>
<input type="text" id="sex" name="sex" /><br>
<input type="submit" value="提交" />
</form>
</body>
</html>
```
insertStudent.jsp:
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert Student</title>
</head>
<body>
<%
String url="jdbc:sqlserver://localhost;databaseName=StudentInfo";
request.setCharacterEncoding("utf-8");
String sno = request.getParameter("sno");
String sname = request.getParameter("sname");
int sage = Integer.valueOf(request.getParameter("sage"));
String sex = request.getParameter("sex");
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url,"sa","123");
String sql = "insert into student values(?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, sno);
pstmt.setString(2, sname);
pstmt.setInt(3, sage);
pstmt.setString(4, sex);
int num = pstmt.executeUpdate();
if(num > 0){
out.print("插入成功!");
}
pstmt.close();
conn.close();
}
catch(SQLException ex){
System.out.println ("\n*** 发生SQL异常 ***\n"+ex.getMessage());
}
catch(ClassNotFoundException ex){
System.out.println(ex);
}
%>
</body>
</html>
```
阅读全文