How do I enter data from an HTML form into MySQL using JDBC?

Question:

There are 2 HTML forms

<input type="text" name="login" size="45" /> 

and

<input type="password" name="password" size="45" />

Database on MySQL Server , where similar fields login varchar (45) NOT NULL and password varchar (45) NOT NULL are present.

Tell me how to use JDBC to write HTML form data to a MySQL . PHP not offered, other Java technologies are possible.

Answer:

Quick implementation using a servlet:

html

<html>
    <head>
        <meta charset="utf-8">
        <link type="text/css" href="style.css">
    </head>
    <body id="body"> 
        <form method="post" action="TheFirstServlet">    
            <input name="login">
            <input name="password">
            <button>Записать</button>
        </form>
    </body>
</html>

TheFirstServlet

public class FirstServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    }

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");  
    String login = request.getParameter("login");
    String password = request.getParameter("password");  
    insert(login, password);
    PrintWriter printWriter;
    try {
        printWriter = response.getWriter(); 
        printWriter.println("Ну, попытались");
    } catch(IOException exc) {}
}

public void insert(String login, String password) {
    Connection conn = null;
    Statement stmt = null;
    try {
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc.url", "jdbc.login", "jdbc.password");
    stmt = conn.createStatement();
    String sql = "INSERT INTO NAME_TABLE (`login`,`password`)" +
            "VALUES ('" + login + "','" + password + "')";
    stmt.executeUpdate(sql);
    } catch (SQLException | ClassNotFoundException exc) {
        exc.printStackTrace();
        System.out.println("Не записал");
    }
    finally {
        try {
            if(conn!=null) conn.close();
            if(stmt!=null) stmt.close();
        } catch (SQLException exc) {}
    }
  }

Well, somehow so simple.

Scroll to Top