本文共 1844 字,大约阅读时间需要 6 分钟。
packagecom.jquery.register;importjava.io.IOException;importjava.io.PrintWriter;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;public class add extendsHttpServlet {public voiddestroy() {super.destroy();
}public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
doPost(request,response);
}public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Connection conn= null;
PreparedStatement stmt= null;
ResultSet rs= null;
String name=request.getParameter("name");
String password=request.getParameter("password");
String drive= "com.mysql.jdbc.Driver";
System.out.println("ajax后台交互成功");try{
Class.forName(drive);
conn=DriverManager
.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=123");
System.out.println("数据库连接成功");
String sql="insert into user_table(name,password)";
sql+=" values(?,?)";
stmt=conn.prepareStatement(sql);
stmt.setString(1,name);
stmt.setString(2,password);
stmt.executeUpdate();
System.out.println("success");//out.flush();//out.close();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}finally{try{//注意关闭原则:从里到外
if (rs != null) {
rs.close();
}if (stmt != null) {
stmt.close();
}if (conn != null) {
conn.close();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}public void init() throwsServletException {//Put your code here
}
}
转载地址:http://rihhv.baihongyu.com/