Cara Membuat CRUD Sederhana Dengan JAVA Netbeans MySQL
Pada postingan ini saya akan berbagi cara membuat proses CRUD menggunakan JAVA Netbeans dan MySQL database. disini sayang menggunakan NetBeans versi 8.0.2.
Ok langsung saja.
1. Buat Project Baru di NetBeans dengan NAMA CRUD (pilih java application) karena kita akan membuat dekstop app.
2. Buat class koneksi database java dengan MySql
sebelum membuat class koneksi kita import library mysql dulu dengan cara klik kanan pada library kemudian add libarary -> pilih MySQL JDBC Driver,
setelah itu buat class koneksi seperti berikut :
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author Husnul-M
*/
public class koneksi {
private static Connection mysqlkonek;
public static Connection koneksiDB() throws SQLException {
if(mysqlkonek==null){
try {
String DB="jdbc:mysql://localhost:3306/tketik"; // delta_db database
String user="root"; // user database
String pass=""; // password database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
mysqlkonek = (Connection) DriverManager.getConnection(DB,user,pass);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"gagal koneksi");
}
}
return mysqlkonek;
}
}
3. Buat JFrame Form baru dengan nama MainForm dan design layoutnya seperti berikut :
setelah design form selesai tambahkan source code berikut didalam MainForm
import java.sql.Connection;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class MainForm extends javax.swing.JFrame {
Mhs idmhs = new Mhs();
int hmid;
/**
* Creates new form MainForm
*/
public MainForm() {
initComponents();
load_table();
kosong();
hmid = 0;
}
/**
* 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();
jLabel1 = new javax.swing.JLabel();
txtNama = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtAlamat = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtPekerjaan = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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"
}
));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
jLabel1.setText("Nama");
txtNama.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNamaActionPerformed(evt);
}
});
jLabel2.setText("Alamat");
jLabel3.setText("Pekerjaan");
jButton1.setText("Simpan");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Edit");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Hapus");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtNama)
.addComponent(txtAlamat)
.addComponent(txtPekerjaan, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtNama, 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.BASELINE)
.addComponent(jLabel2)
.addComponent(txtAlamat, 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.BASELINE)
.addComponent(jLabel3)
.addComponent(txtPekerjaan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(41, 41, 41)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
private void txtNamaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "INSERT INTO mhs(nama,alamat,pekerjaan) VALUES ('" + txtNama.getText() + "','" + txtAlamat.getText() + "','" + txtPekerjaan.getText() + "')";
java.sql.Connection conn = (Connection) koneksi.koneksiDB();
java.sql.PreparedStatement pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "Penyimpanan Data Berhasil");
load_table();
kosong();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
int baris = jTable1.rowAtPoint(evt.getPoint());
String ids = jTable1.getValueAt(baris, 0).toString();
String nama = jTable1.getValueAt(baris, 1).toString();
txtNama.setText(nama);
String alamat = jTable1.getValueAt(baris, 2).toString();
txtAlamat.setText(alamat);
String pekerjaan = jTable1.getValueAt(baris, 3).toString();
txtPekerjaan.setText(pekerjaan);
hmid = Integer.parseInt(ids);
// idmhs.setId(ids);
// JOptionPane.showMessageDialog(null, hmid, "Alert", JOptionPane.INFORMATION_MESSAGE);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "UPDATE mhs SET nama = '" + txtNama.getText() + "', alamat = '" + txtAlamat.getText() + "',pekerjaan= '" + txtPekerjaan.getText() + "' WHERE id = '" + hmid + "'";
java.sql.Connection conn = (Connection) koneksi.koneksiDB();
java.sql.PreparedStatement pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "data berhasil di edit");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Perubahan Data Gagal" + e.getMessage());
}
load_table();
kosong();
hmid = 0;
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
if (hmid == 0) {
JOptionPane.showMessageDialog(null, "Pilih Data Bro", "Alert", JOptionPane.ERROR_MESSAGE);
} else {
String sql = "Delete From mhs WHERE id = '" + hmid + "'";
java.sql.Connection conn = (Connection) koneksi.koneksiDB();
java.sql.PreparedStatement pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "data berhasil di hapus");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Perubahan Data Gagal" + e.getMessage());
}
load_table();
kosong();
hmid = 0;
}
private void load_table() {
// membuat tampilan model tabel
DefaultTableModel model = new DefaultTableModel();
model.addColumn("No");
model.addColumn("Nama");
model.addColumn("Alamat");
model.addColumn("Pekerjaan");
//menampilkan data database kedalam tabel
try {
int no = 1;
String sql = "select * from mhs";
java.sql.Connection conn = (Connection) koneksi.koneksiDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next()) {
model.addRow(new Object[]{res.getString(1), res.getString(2), res.getString(3), res.getString(4)});
}
jTable1.setModel(model);
} catch (Exception e) {
}
}
private void kosong() {
txtNama.setText(null);
txtAlamat.setText(null);
txtPekerjaan.setText(null);
hmid = 0;
}
/**
* @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(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.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 MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtAlamat;
private javax.swing.JTextField txtNama;
private javax.swing.JTextField txtPekerjaan;
// End of variables declaration
}
4. Desian MySql Table
Ok cukup sekian sharing kali ini semoga bermanfaat, terimakasih :D
terimakasih gan sudah berkunjung
ReplyDeletehmmm kurang di mengerti :(
ReplyDeletemantul
ReplyDeleteGan...iku cara buat database nya gmna...
ReplyDeletevisit this link
ReplyDeletehttps://jatimtimes.com
https://malangtimes.com
https://jatimtimes.com/baca/238215/20210324/121100/polisi-tangkap-terduga-pembunuh-wanita-yang-ditemukan-setengah-telanjang-di-pakisaji