Fri. Oct 22nd, 2021

Pada materi ini yaitu membuat aplikasi sederhana dengan menggunakan java dan database MYSQL. pertama silahkan buat database dengan nama konekjava

kemudian buat lah table dengan nama data_mahasiswa dengan jumlah kolom 4

buatlah field pada tabel tersebut

Setelah selesai membuat database maka selanjutnya coding di java.

buat project, kemudian tambahkan library MYSQL JDBC pada libraries dengan cara klik kanan kemudian pilih add Library

kemudian pilih MYSQL JDBC DRIVER

Setelah itu buatlah class dengan nama Koneksi.java adapun codenya sebagai berikut

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package formdatabase;

/**
 *
 * @author ASUS
 */
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

public class Koneksi {
    Connection koneksi;
    
    public static Connection Koneksi() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection koneksi = DriverManager.getConnection("jdbc:mysql://localhost/konekjava", "root", "");
            
            return koneksi;
        } catch(Exception e) {
            JOptionPane.showMessageDialog(null, e);
            
            return null;
        }
    }
}

pada driver manager sesuaikan dengan nama database yang dibuat yaitu konekjava.

Setelah itu buatlah Jframe untuk Layoutnya

Buatlah desain seperti gambar diabawah ini yang terdiri dari label, Textfield, Table dan Button

kemudian buatlah change variable name dengan cara mengklik kanan pada textfield dan button

isiannya variabelnya inputnpm, inputnama, inputalamat, inputtelpon, btn_simpan, btn_update, btn_hapus dan btn_reset

masukkan import pada jframe

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

dan pada konstruktor awal masukkan

public class Inputmahasiswa extends javax.swing.JFrame {

    /**
     * Creates new form Inputmahasiswa
     */
     public Statement st;
    public ResultSet rs;
    public DefaultTableModel tabModel;
    Connection cn = Koneksi.Koneksi();
    public Inputmahasiswa() {
        initComponents();
          judul();
  tampilData("");
  
  btn_hapus.setEnabled(false);
  btn_update.setEnabled(false);
        
    }

setelah itu buat method judul dan tampil data pada jframe

 public void judul() {
  Object[] judul = {
    "npm", "nama", "alamat", "telpon"
  };
  tabModel = new DefaultTableModel(null, judul);
  tablemhs.setModel(tabModel);
}

public void tampilData(String where) {
  try {
    st = cn.createStatement();
    tabModel.getDataVector().removeAllElements();
    tabModel.fireTableDataChanged();
    rs = st.executeQuery("SELECT * FROM data_mahasiswa " + where);
    
    while (rs.next()) {
      Object[] data = {
        rs.getString("npm"),
        rs.getString("nama"),
        rs.getString("alamat"),
        rs.getString("telpon"),

      };
        
        tabModel.addRow(data);
    }
  } catch(Exception e) {
    e.printStackTrace();
  }
}

kemudian buat code untuk Button SIMPAN, dengan cara klik 2x button SIMPAN dan masukkan code

 try {
  st = cn.createStatement();
  st.executeUpdate("INSERT INTO data_mahasiswa VALUES('" + inputnpm.getText() + "','"
      + inputnama.getText() + "','"
      + inputalamat.getText() + "','"
      + inputtelpon.getText() + "')");
  tampilData("");
  JOptionPane.showMessageDialog(null, "Simpan Berhasil");
  inputnpm.setText("");
  inputnama.setText("");
  inputalamat.setText("");
  inputtelpon.setText("");

} catch (Exception e) {
  e.printStackTrace();
}

 

setelah itu buatlah code untuk edit, namun sebelum mengeksekusi button update maka pada table perlu dibuat event mouse click dengan cara

kemduian masukkan code

  inputnpm.setText(tablemhs.getValueAt(tablemhs.getSelectedRow(), 0).toString());
  inputnama.setText(tablemhs.getValueAt(tablemhs.getSelectedRow(), 1).toString());
inputalamat.setText(tablemhs.getValueAt(tablemhs.getSelectedRow(), 2).toString());
  inputtelpon.setText(tablemhs.getValueAt(tablemhs.getSelectedRow(), 3).toString());
  btn_simpan.setEnabled(false);
  btn_update.setEnabled(true);
  btn_hapus.setEnabled(true);

setelah itu buatlah action pada buttun Update dengan cara klik2x pada button update dan memasukkan code

   try {
 st = cn.createStatement();
 st.executeUpdate("UPDATE data_mahasiswa set " 
 + "nama='" + inputnama.getText() + "', "
 + "alamat='" + inputalamat.getText() + "', "
 + "telpon='" + inputtelpon.getText() + "'"
 +"Where npm='" + inputnpm.getText() + "'" );
 tampilData("");
 JOptionPane.showMessageDialog(null, "Update Berhasil");
 inputnpm.setText("");
 inputnama.setText("");
 inputalamat.setText("");
 inputtelpon.setText("");
 } catch (Exception e) {
 e.printStackTrace();
 }

Buat juga code untuk Hapus. dengan cara klik 2x pada button hapus dan masukkan code:

 try {
  int tanya;
  
  if ((tanya = JOptionPane.showConfirmDialog(null, "Hapus Data Mahasiswa ini?", "konfirmasi", JOptionPane.YES_NO_OPTION)) == 0) {
    st = cn.createStatement();
    st.executeUpdate("DELETE FROM data_mahasiswa WHERE npm='"
        + tabModel.getValueAt(tablemhs.getSelectedRow(), 0) + "'");
    tampilData("");
      inputnpm.setText("");
      inputnama.setText("");
      inputalamat.setText("");
      inputtelpon.setText("");
  }
} catch (Exception e) {
  e.printStackTrace();
}

untuk button reset

inputnpm.setText("");
        inputnama.setText("");
        inputalamat.setText("");
        inputtelpon.setText("");

 

Source Code Detil Sebagai Berikut:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package formdatabase;

/**
 *
 * @author ASUS
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class Inputmahasiswa extends javax.swing.JFrame {

 /**
 * Creates new form Inputmahasiswa
 */
 public Statement st;
 public ResultSet rs;
 public DefaultTableModel tabModel;
 Connection cn = Koneksi.Koneksi();
 public Inputmahasiswa() {
 initComponents();
 judul();
 tampilData("");
 
 btn_hapus.setEnabled(false);
 btn_update.setEnabled(false);
 
 }
 
 public void judul() {
 Object[] judul = {
 "npm", "nama", "alamat", "telpon"
 };
 tabModel = new DefaultTableModel(null, judul);
 tablemhs.setModel(tabModel);
}

public void tampilData(String where) {
 try {
 st = cn.createStatement();
 tabModel.getDataVector().removeAllElements();
 tabModel.fireTableDataChanged();
 rs = st.executeQuery("SELECT * FROM data_mahasiswa " + where);
 
 while (rs.next()) {
 Object[] data = {
 rs.getString("npm"),
 rs.getString("nama"),
 rs.getString("alamat"),
 rs.getString("telpon"),

 };
 
 tabModel.addRow(data);
 }
 } catch(Exception e) {
 e.printStackTrace();
 }
}

 /**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
 @SuppressWarnings("unchecked")
 // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
 private void initComponents() {

 jScrollPane1 = new javax.swing.JScrollPane();
 jTable1 = new javax.swing.JTable();
 jScrollPane2 = new javax.swing.JScrollPane();
 jTable2 = new javax.swing.JTable();
 jLabel1 = new javax.swing.JLabel();
 inputnama = new javax.swing.JTextField();
 jLabel2 = new javax.swing.JLabel();
 inputnpm = new javax.swing.JTextField();
 jLabel3 = new javax.swing.JLabel();
 inputalamat = new javax.swing.JTextField();
 jLabel4 = new javax.swing.JLabel();
 inputtelpon = new javax.swing.JTextField();
 btn_simpan = new javax.swing.JButton();
 btn_update = new javax.swing.JButton();
 btn_hapus = new javax.swing.JButton();
 btn_reset = new javax.swing.JButton();
 jScrollPane3 = new javax.swing.JScrollPane();
 tablemhs = new javax.swing.JTable();

 jTable1.setModel(new javax.swing.table.DefaultTableModel(
 new Object [][] {
 {null, null, null, null},
 {null, null, null, null},
 {null, null, null, null},
 {null, null, null, null}
 },
 new String [] {
 "Title 1", "Title 2", "Title 3", "Title 4"
 }
 ));
 jScrollPane1.setViewportView(jTable1);

 jTable2.setModel(new javax.swing.table.DefaultTableModel(
 new Object [][] {
 {null, null, null, null},
 {null, null, null, null},
 {null, null, null, null},
 {null, null, null, null}
 },
 new String [] {
 "Title 1", "Title 2", "Title 3", "Title 4"
 }
 ));
 jScrollPane2.setViewportView(jTable2);

 setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

 jLabel1.setText("Nama");

 inputnama.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 inputnamaActionPerformed(evt);
 }
 });

 jLabel2.setText("NPM");

 jLabel3.setText("Alamat");

 inputalamat.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 inputalamatActionPerformed(evt);
 }
 });

 jLabel4.setText("No Telpon");

 btn_simpan.setText("SIMPAN");
 btn_simpan.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 btn_simpanActionPerformed(evt);
 }
 });

 btn_update.setText("UPDATE");
 btn_update.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 btn_updateActionPerformed(evt);
 }
 });

 btn_hapus.setText("HAPUS");
 btn_hapus.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 btn_hapusActionPerformed(evt);
 }
 });

 btn_reset.setText("RESET");
 btn_reset.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 btn_resetActionPerformed(evt);
 }
 });

 tablemhs.setModel(new javax.swing.table.DefaultTableModel(
 new Object [][] {
 {null, null, null, null},
 {null, null, null, null},
 {null, null, null, null},
 {null, null, null, null}
 },
 new String [] {
 "Title 1", "Title 2", "Title 3", "Title 4"
 }
 ));
 tablemhs.addMouseListener(new java.awt.event.MouseAdapter() {
 public void mouseClicked(java.awt.event.MouseEvent evt) {
 tablemhsMouseClicked(evt);
 }
 });
 jScrollPane3.setViewportView(tablemhs);

 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
 getContentPane().setLayout(layout);
 layout.setHorizontalGroup(
 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addGap(23, 23, 23)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addComponent(btn_simpan)
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
 .addComponent(btn_update)
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
 .addComponent(btn_hapus)
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
 .addComponent(btn_reset))
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
 .addGroup(layout.createSequentialGroup()
 .addComponent(jLabel4)
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
 .addComponent(inputtelpon, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
 .addGroup(layout.createSequentialGroup()
 .addComponent(jLabel3)
 .addGap(25, 25, 25)
 .addComponent(inputalamat))
 .addGroup(layout.createSequentialGroup()
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
 .addComponent(jLabel2)
 .addComponent(jLabel1))
 .addGap(31, 31, 31)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
 .addComponent(inputnpm, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
 .addComponent(inputnama))))))
 .addGroup(layout.createSequentialGroup()
 .addContainerGap()
 .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 414, javax.swing.GroupLayout.PREFERRED_SIZE)))
 .addContainerGap(15, Short.MAX_VALUE))
 );
 layout.setVerticalGroup(
 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addGap(18, 18, 18)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
 .addComponent(jLabel1)
 .addComponent(inputnama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addComponent(jLabel2)
 .addComponent(inputnpm, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
 .addGap(18, 18, 18)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
 .addComponent(jLabel3)
 .addComponent(inputalamat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
 .addGap(18, 18, 18)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
 .addComponent(jLabel4)
 .addComponent(inputtelpon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
 .addGap(18, 18, 18)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
 .addComponent(btn_simpan)
 .addComponent(btn_update)
 .addComponent(btn_hapus)
 .addComponent(btn_reset))
 .addGap(96, 96, 96)
 .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
 );

 pack();
 }// </editor-fold> 

 private void inputnamaActionPerformed(java.awt.event.ActionEvent evt) { 
 // TODO add your handling code here:
 } 

 private void inputalamatActionPerformed(java.awt.event.ActionEvent evt) { 
 // TODO add your handling code here:
 } 

 private void btn_simpanActionPerformed(java.awt.event.ActionEvent evt) { 
 // TODO add your handling code here:
 try {
 st = cn.createStatement();
 st.executeUpdate("INSERT INTO data_mahasiswa VALUES('" + inputnpm.getText() + "','"
 + inputnama.getText() + "','"
 + inputalamat.getText() + "','"
 + inputtelpon.getText() + "')");
 tampilData("");
 JOptionPane.showMessageDialog(null, "Simpan Berhasil");
 inputnpm.setText("");
 inputnama.setText("");
 inputalamat.setText("");
 inputtelpon.setText("");

 } catch (Exception e) {
 e.printStackTrace();
 }
 } 

 private void tablemhsMouseClicked(java.awt.event.MouseEvent evt) { 
 // TODO add your handling code here:
 inputnpm.setText(tablemhs.getValueAt(tablemhs.getSelectedRow(), 0).toString());
 inputnama.setText(tablemhs.getValueAt(tablemhs.getSelectedRow(), 1).toString());
inputalamat.setText(tablemhs.getValueAt(tablemhs.getSelectedRow(), 2).toString());
 inputtelpon.setText(tablemhs.getValueAt(tablemhs.getSelectedRow(), 3).toString());
 btn_simpan.setEnabled(false);
 btn_update.setEnabled(true);
 btn_hapus.setEnabled(true);
 } 

 private void btn_resetActionPerformed(java.awt.event.ActionEvent evt) { 
 // TODO add your handling code here:
 inputnpm.setText("");
 inputnama.setText("");
 inputalamat.setText("");
 inputtelpon.setText("");
 } 

 private void btn_updateActionPerformed(java.awt.event.ActionEvent evt) { 
 // TODO add your handling code here:
 try {
 st = cn.createStatement();
 st.executeUpdate("UPDATE data_mahasiswa set " 
 + "nama='" + inputnama.getText() + "', "
 + "alamat='" + inputalamat.getText() + "', "
 + "telpon='" + inputtelpon.getText() + "'"
 +"Where npm='" + inputnpm.getText() + "'" );
 tampilData("");
 JOptionPane.showMessageDialog(null, "Update Berhasil");
 inputnpm.setText("");
 inputnama.setText("");
 inputalamat.setText("");
 inputtelpon.setText("");
 } catch (Exception e) {
 e.printStackTrace();
 }
 } 

 private void btn_hapusActionPerformed(java.awt.event.ActionEvent evt) { 
 // TODO add your handling code here:
 try {
 int tanya;
 
 if ((tanya = JOptionPane.showConfirmDialog(null, "Hapus Data Mahasiswa ini?", "konfirmasi", JOptionPane.YES_NO_OPTION)) == 0) {
 st = cn.createStatement();
 st.executeUpdate("DELETE FROM data_mahasiswa WHERE npm='"
 + tabModel.getValueAt(tablemhs.getSelectedRow(), 0) + "'");
 tampilData("");
 inputnpm.setText("");
 inputnama.setText("");
 inputalamat.setText("");
 inputtelpon.setText("");
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 } 

 /**
 * @param args the command line arguments
 */
 public static void main(String args[]) {
 /* Set the Nimbus look and feel */
 //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
 /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
 */
 try {
 for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
 if ("Nimbus".equals(info.getName())) {
 javax.swing.UIManager.setLookAndFeel(info.getClassName());
 break;
 }
 }
 } catch (ClassNotFoundException ex) {
 java.util.logging.Logger.getLogger(Inputmahasiswa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 } catch (InstantiationException ex) {
 java.util.logging.Logger.getLogger(Inputmahasiswa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 } catch (IllegalAccessException ex) {
 java.util.logging.Logger.getLogger(Inputmahasiswa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 } catch (javax.swing.UnsupportedLookAndFeelException ex) {
 java.util.logging.Logger.getLogger(Inputmahasiswa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 }
 //</editor-fold>

 /* Create and display the form */
 java.awt.EventQueue.invokeLater(new Runnable() {
 public void run() {
 new Inputmahasiswa().setVisible(true);
 }
 });
 }

 // Variables declaration - do not modify 
 private javax.swing.JButton btn_hapus;
 private javax.swing.JButton btn_reset;
 private javax.swing.JButton btn_simpan;
 private javax.swing.JButton btn_update;
 private javax.swing.JTextField inputalamat;
 private javax.swing.JTextField inputnama;
 private javax.swing.JTextField inputnpm;
 private javax.swing.JTextField inputtelpon;
 private javax.swing.JLabel jLabel1;
 private javax.swing.JLabel jLabel2;
 private javax.swing.JLabel jLabel3;
 private javax.swing.JLabel jLabel4;
 private javax.swing.JScrollPane jScrollPane1;
 private javax.swing.JScrollPane jScrollPane2;
 private javax.swing.JScrollPane jScrollPane3;
 private javax.swing.JTable jTable1;
 private javax.swing.JTable jTable2;
 private javax.swing.JTable tablemhs;
 // End of variables declaration 
}

Hasil Ketika Data di simpan

Hasil Ketika Data di update

Ketika Data di Hapus