JSP+JDBC实现在可视化页面中插入数据到SQL数据库
原创
本篇博客创建一个如下图所示的JSP页面,将用户填入的数据插入到对应的数据库中。
JSP页面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>输入界面</title> </head> <body> 请填写需要插入的数据:<br><br> <form action="recept.jsp" method="post"> 学号:<input type="text" name="id"><br><br> 姓名:<input type="text" name="name"><br><br> 性别:<input type="text" name="sex"><br><br> 年龄:<input type="text" name="age"><br><br> 体重:<input type="text" name="weight"><br><br> 身高:<input type="text" name="hight"><br><br> <input type="submit" value="提交"> <input type="reset" value="取消"> </form> </body> </html>
JDBC代码:
<%@ page language="java" import="java.sql.*,java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>接收页面</title> </head> <body> <% //连接数据库 String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver"; String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=DB OF CWM"; String userName="sa"; String pwd="dearcwm*0."; Class.forName(driverName); Connection conn=DriverManager.getConnection(dbURL,userName,pwd); String sql="insert into stu_info(id,name,sex,age,weight,hight)values(?,?,?,?,?,?)"; PreparedStatement stmp=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")); stmp.setInt(1,id); stmp.setString(2,name); stmp.setString(3,sex); stmp.setInt(4,age); stmp.setFloat(5,weight); stmp.setFloat(6,hight); int n=stmp.executeUpdate(); if(n==1){ %> 数据插入操作成功!<% } %><%else{ %>数据插入操作失败!<%} if(stmp!=null){ stmp.close(); } if(conn!=null){ conn.close(); } %> </body> </html>
16:25:16
2018-09-30