Pada artikel ini, saya menulis artikel tentang cara menyimpan data ke database MySQL menggunakan JDBC melalui servlet 3. Hal pertama yang perlu dilakukan adalah membuat database dan tabel di MySQL.

create database belajar;

use belajar;

create table barang(
     id integer primary key auto_increment,
     nama varchar(100) not null,
     harga_beli integer not null,
     harga_jual integer not null
)type=InnoDB;
 
Selanjutnya buatlah koneksi ke database yang telah dibuat, kita akan menggunakan WebListener untuk membuat koneksi tersebut.

package khannedy.web.listener;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ConnectionListener implements ServletContextListener {

    public static final String CONNECTION_KEY = "your_connection_key";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/belajar", "root", "root");
            sce.getServletContext().setAttribute(CONNECTION_KEY, connection);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            Connection connection = (Connection) sce.getServletContext().getAttribute(CONNECTION_KEY);
            connection.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}


Setelah itu buat halaman HTML untuk menampung input data yang akan dikirim ke servlet
 
<!doctype html>
<html>
    <head>
        <title>Menambah Data</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <h1>Tambah Data Barang</h1>
        <form method="post" action="SaveData">
            <table>
                <tbody>
                    <tr>
                        <td>Nama</td>
                        <td><input type="text" name="nama"/></td>
                    </tr>
                    <tr>
                        <td>Harga Beli</td>
                        <td><input type="text" name="harga_beli"/></td>
                    </tr>
                    <tr>
                        <td>Harga Jual</td>
                        <td><input type="text" name="harga_jual"/></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td><input type="submit" value="Process"/></td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>

Setelah itu, buat servlet dimana digunakan untuk melakukan proses simpan data ke database MySQL.
 
package khannedy.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import khannedy.web.listener.ConnectionListener;

@WebServlet(name = "SaveData", urlPatterns = {"/SaveData"})
public class SaveDataServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            Connection connection = (Connection) getServletContext().getAttribute(ConnectionListener.CONNECTION_KEY);

            String sql = "insert into barang (nama, harga_beli, harga_jual) values (?, ?, ?);";

            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, request.getParameter("nama"));
            statement.setInt(2, Integer.parseInt(request.getParameter("harga_beli")));
            statement.setInt(3, Integer.parseInt(request.getParameter("harga_jual")));
            statement.executeUpdate();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SaveDataServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Berhasil Menambah Data Barang</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }
}
Hasilnya :
Screenshot-Menambah Data - Google Chrome
Screenshot-Menambah Data - Google Chrome
Screenshot-Servlet SaveDataServlet - Google Chrome
Screenshot-Servlet SaveDataServlet - Google Chrome
Screenshot-echo@echo-ubuntu: ~ - Terminal
Screenshot-echo@echo-ubuntu: ~ - Terminal


EmoticonEmoticon