我是java web的新手。我想编写简单的登录页面,将数据插入到MySql中。当我运行代码时,一切运行正常,但是数据int插入到数据库中。我现在搜索了大约2天但是无法解决它。谢谢你的帮助 首先是我的数据库类名是MyDb,第二个是server.Also我的id是自动增量
#1
Connection conn;
public Connection getCon(){
try {
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection("jdbc:mysql://localhost:3306/sign_up", "root", "12345");
System.out.println("connection is done");
} catch (ClassNotFoundException ex) {
Logger.getLogger(MyDb.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(MyDb.class.getName()).log(Level.SEVERE, null, ex);
}
return conn;
}
#2
public class registr extends HttpServlet {
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String name = request.getParameter("name");
String username = request.getParameter("username")
String password = request.getParameter("password");
String email = request.getParameter("email");
MyDb db = new MyDb();
Connection conn = db.getCon();
conn.setAutoCommit(true);
String query = "INSERT INTO sign(name, surname, email, password)" + "VALUES(?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, username);
stmt.setString(3, password);
stmt.setString(4, email);
stmt.executeUpdate(query);
} catch (SQLException ex) {
Logger.getLogger(registr.class.getName()).log(Level.SEVERE,null,ex);
}
}
答案 0 :(得分:0)
更改stmt.executeUpdate(query)
;到stmt.executeUpdate();
答案 1 :(得分:0)
如果你发布了所有的Servlet类代码,那么你就会遗漏一些东西。官方Servlet接口不会自动调用processRequest
方法。以下是HttpServlet的JavaDoc摘录:
公共抽象类HttpServlet扩展GenericServlet实现java.io.Serializable
提供要进行子类化的抽象类,以创建适用于Web站点的HTTP Servlet。 HttpServlet的子类必须至少覆盖一个方法,通常是以下方法之一:
doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
init and destroy, to manage resources that are held for the life of the servlet
getServletInfo, which the servlet uses to provide information about itself
几乎没有理由覆盖服务方法。 service通过将它们分派给每个HTTP请求类型的处理程序方法(上面列出的doXXX方法)来处理标准HTTP请求。
所以你要做的就是改变你的Servlet,例如,如下
public class registr extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
processRequest(req, res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
processRequest(req, res);
}
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// your code
}
}
提示:Java编码对话表明类的名称应该以大写字母开头,即代替registr
它应该是Registr
。