<span style="font-size:18px;">package org.csu;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Selectservlet extends HttpServlet {
private static final String CONTENT_TYPE="text/html;charset=GBK";
public void init() throws ServletException {
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
String name = request.getParameter("name");
//得到请求参数
String grent = request.getParameter("grent");
String result = request.getParameter("result");
try{ //链接数据库
Class.forName("org.gjt.mm.mysql.Driver");
String url;
url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GB2312";
String user= "root";
String password = "root";
Connection con= DriverManager.getConnection(url,user,password);
Statement rs = con.createStatement();
String sql = "insert into student values('"+name+"','"+grent+"','"+result+"');";
int length = rs.executeUpdate(sql);
if(length!=0) { //插入数据
out.println("添加成功!!!");
ResultSet s = rs.executeQuery("select * from student");
out.println("<html>");
out.println("<head><title>selectservlet</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<table align='center' border='1'><tr><td>姓名</td><td>班级</td><td>成绩</td><td>修改</td><td>删除</td></tr>");
while(s.next()) { //遍历数据在页面上显示
out.println("<tr><td>"+s.getString("name")+"</td><td>"+s.getString("grent")+"</td><td>"+s.getString("result")+
"</td><td><a href=update?name="+s.getString("name")+">修改</a></td><td><a href=delete?name="+s.getString("name")
+">删除</a></td></tr>");
}
out.println("</table>");
out.println("<body>");
out.println("</html>");
}else {
out.println("添加 失败!!!");
}
}catch(Exception ce) {
ce.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void destroy() {
}
}
</span>
<html>
<body>
<form action="./Selectservlet" method="get">
<table border=1>
<tr>
<td>姓名:</td>
<td>班级:</td>
<td>成绩:</td>
<td>修改:</td>
<td>删除:</td>
</tr>
<tr>
<td><input type="text" name="name" value="Bmy"></td>
<td><input type="text" name="grent" value="0802"></td>
<td><input type="text" name="result" value="73"></td>
<td>修改</td>
<td>删除</td>
</tr>
</table>
<input type="submit" value="提交" >
</form>
</body>
</html>
结果:一条数据成功插入到Mysql中。
对于此刻的我来说,学东西总是不踏实,不够耐心,因此基础不够牢固。以上代码有很多的修改的空间。再接再厉吧!!