對資料庫進行插入操作
阿新 • • 發佈:2018-11-10
提交.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>新增任意學生的提交頁面</title> </head> <body> <form action="提交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>
提交2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.sql.*"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>利用PreparedStatement物件新增並建立資料庫的連線</title> </head> <body> <% String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"; String user="sa"; String password="zqb19971023"; String url="jdbc:sqlserver://localhost:1433;DatabaseName=666"; Connection conn=null; try{ Class.forName(driver); conn=DriverManager.getConnection(url, user, password); System.out.println("連線成功"); }catch(Exception e) { System.out.println("連線失敗"); } request.setCharacterEncoding("UTF-8"); String sql="Insert into stu1(id,name,sex,age,weight,hight) values(?,?,?,?,?,?)"; PreparedStatement pstmt=conn.prepareStatement(sql); int id=Integer.parseInt(request.getParameter("id")); String name=request.getParameter("name"); String sex=request.getParameter("sex"); String age=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.setString(4,age); pstmt.setFloat(5, weight); pstmt.setFloat(6,hight); int n; n=pstmt.executeUpdate(); if(n==1){ %> 資料插入操作成功!<br><% }else{ %> 資料插入操作失敗!<br> <% } if(pstmt!=null){ pstmt.close();} if(conn!=null){ conn.close();} %> </body> </html>