我必须使用servlet Java Web应用程序在mysql数据库上执行crud操作,因此我从插入操作开始,但无法正常工作
这是我的html形式:
<form action="insertservlet">
<input type="text" name="fname" /><br>
<input type="text" name="lname" /><br>
<input type="submit" value="insert">
这是insertservlet dopost代码
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " + cnfe);
}
String dbURL = "jdbc:mysql:// localhost:3306/dbase";
String username = "root";
String password = "1234";
try {
Connection connection = DriverManager.getConnection(dbURL, username, password);
Statement statement = connection.createStatement();
String query = "insert into user(fname,lname) values(" + fname + "," + lname + ")";
statement.executeQuery(query);
} catch (SQLException ex) {
Logger.getLogger(insertservlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
但表中没有插入数据
MySQL服务器在cmd上运行
问题的根本原因是在表单操作中未包含method="post"
;应该是
<form action="insertservlet" method="post">
注意,默认动作是get
。
有时,为避免此类问题,如果doPost
为空,人们只需从doGet
调用doGet
。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
附带说明,从JDBC 4.0开始,不需要Class.forName()
。