mysql----資料提交
insert_stu_2_tijiao:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head> <title>新增任意學生的提交頁面</title> </head>
<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:
<%@ 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 = "123456"; //密碼
String dbName = "students"; //資料庫名
String url1="jdbc:mysql://localhost:3306/"+dbName;
String url2 ="?user="+userName+"&password="+userPwd;
String url3="&useUnicode=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);
try{
int n=pstmt.executeUpdate();
if(n==1){%>
資料插入操作成功!<br>
<%}
else{%>
資料插入操作失敗!<br>
<%}
}catch(Exception e){%>
更新過程出現異常錯誤!<br>
<%=e.getMessage()%>
<%;
}
if(pstmt!=null){ pstmt.close(); }
if(conn!=null){ conn.close(); }
%>
</body>
</html>