[使用servlet插入mysql数据库

问题描述 投票:0回答:1

我必须使用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上运行

enter image description here

mysql servlets
1个回答
0
投票

问题的根本原因是在表单操作中未包含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()

© www.soinside.com 2019 - 2024. All rights reserved.