Anda di halaman 1dari 15

Pembuatan CRUD Sistem Informasi Siswa di NetBeans

Pertama kita buat databasenya dahulu. silahkan masuk keroot database anda. menggunakan console/command prompt bisa atau menggunakan phpmyadmin juga boleh : dibawah saya contohkan yang menggunakan console. >create database sis; >use sis; >create table siswa(nis varchar(15) primary key not null, nama varchar(50) not null, alamat varchar(100) not null); Selanjutnya kita beralih ke netbeans dan membuat project, untuk penamaan project bebas, berikut salah satu caranya dengan klik File,kemudian klik New Project:

Setelah itu pilih jenis project java yang diinginkan, namun disini kita menggunakan Java Application. Kemudian pemberian nama terhadap project yang kita buat:

Sebelum kita mengelola database pada MySQL kita perlu membuat terlebih dahulu sebuah koneksi yang dalam java dekenal dengan java.sql.Connection. Untuk memasukkan sebuah library untuk drriver MySQL pada netbeans gampang saj. caranya klik kanan pada library milik project yang akan kita gunakan lalu pilih add library :

setelah itu cari library MySQL JDBC Driver lalu klik tombol add library :

Setelah membuat project silahkan buat package package yang dibutuhkan, untuk nama package terserah anda.

Langkah berikutnya pembuatan code pemogramannya, pertama kita buat class Siswa.java dengan code sebagai berikut: package lat1.objek.entity; /** * * @author acusgazerock */ public class Siswa { private String nis;

private String nama; private String alamat; public Siswa(String nis, String nama, String alamat) { this.nis = nis; this.nama = nama; this.alamat = alamat; } public Siswa() { } public String getAlamat() { return alamat; } public void setAlamat(String alamat) { this.alamat = alamat; } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } public String getNis() { return nis; } public void setNis(String nis) { this.nis = nis; } }

Setelah itu buat interface dengan nama SiswaInterface.java. Ingat interface beda dengan class, dan di netbeans untuk membuat interface menggunakan cara New -> Java Interface.

package lat1.objek.model; import java.sql.SQLException; import java.util.List; import lat1.objek.entity.Siswa; /** * * @author acusgazerock */ public interface SiswaInterface { public void connect() throws SQLException; //inget di beri throws SQLException public void disconnect() throws SQLException; public List read() throws SQLException; public void insert(Siswa siswa) throws SQLException; public void update(String nis, Siswa siswa) throws SQLException; public void delete(String nis) throws SQLException; public Siswa read(String nis) throws SQLException; } Setelah interface kita buat implementasi untuk ImplementDatabaseSiswa.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package lat1.objek.model; import lat1.objek.entity.Siswa; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author acusgazerock */ public class ImplementDatabaseSiswa implements SiswaInterface { private String dbHost = "jdbc:mysql://localhost:3306/sis"; private String dbUser = "root"; interfacenya dengan nama class

private String dbPass = ""; private Connection conn; public ImplementDatabaseSiswa() { try { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (InstantiationException ex) { Logger.getLogger(ImplementDatabaseSiswa.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(ImplementDatabaseSiswa.class.getName()).log(Level.SEVERE, null, ex); } } catch (ClassNotFoundException ex) { Logger.getLogger(ImplementDatabaseSiswa.class.getName()).log(Level.SEVERE, null, ex); } } public ImplementDatabaseSiswa(Connection conn) { this.conn = conn; } public void connect() throws SQLException { this.conn = DriverManager.getConnection(dbHost, dbUser, dbPass); } public void disconnect() throws SQLException { this.conn.close(); } public List read() throws SQLException { Statement st = conn.createStatement(); String sql = "select *from siswa"; ResultSet rs = st.executeQuery(sql); List list = new ArrayList(); while (rs.next()) { Siswa newSiswa = new Siswa(); newSiswa.setNis(rs.getString("nis")); newSiswa.setNama(rs.getString("nama")); newSiswa.setAlamat(rs.getString("alamat")); list.add(newSiswa); } return list;

} public void insert(Siswa siswa) throws SQLException { String sql = "insert into siswa (nis, nama, alamat) values(?,?,?);"; PreparedStatement ps = this.conn.prepareStatement(sql); ps.setString(1, siswa.getNis()); ps.setString(2, siswa.getNama()); ps.setString(3, siswa.getAlamat()); ps.executeUpdate(); } public void update(String nis, Siswa siswa) throws SQLException { String sql = "update siswa set nis=?,nama=?,alamat=? where nis=?"; PreparedStatement ps = this.conn.prepareStatement(sql); ps.setString(1, siswa.getNis()); ps.setString(2, siswa.getNama()); ps.setString(3, siswa.getAlamat()); ps.setString(4, nis); ps.executeUpdate(); } public void delete(String nis) throws SQLException { String sql = "delete from siswa where nis=?"; PreparedStatement ps = this.conn.prepareStatement(sql); ps.setString(1, nis); ps.executeUpdate(); } public Siswa read(String nis) throws SQLException { String sql = "select *from siswa where nis = ?"; PreparedStatement ps = this.conn.prepareStatement(sql); ps.setString(1, nis); ResultSet rs = ps.executeQuery(); Siswa siswa = new Siswa(); while (rs.next()) { siswa.setNis(rs.getString("nis")); siswa.setNama(rs.getString("nama")); siswa.setAlamat(rs.getString("alamat")); } return siswa; } }

Setelah itu, sekarang kita buat viewnya atau desaign tampilannya.. silahkan masuk New -> JFrame Form disini saya beri nama FormSiswa.java

package lat1.view; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableModel; import lat1.objek.entity.Siswa; import lat1.objek.model.ImplementDatabaseSiswa; import lat1.objek.model.TabelSiswa; /** * * @author acusgazerock */ public class FormSiswa extends javax.swing.JFrame { /** Creates new form FormSiswa */ public FormSiswa() { initComponents(); } ImplementDatabaseSiswa daoMysql = new ImplementDatabaseSiswa(); TabelSiswa tabelSiswa; List<Siswa> records = new ArrayList<Siswa>(); /** Creates new form FormSiswa */ void loadData() { try { daoMysql.connect();

List list = new ArrayList(); list = daoMysql.read(); TableModel tableSiswa = new TabelSiswa(list); tabelIsiData.setModel(tableSiswa); daoMysql.disconnect(); } catch (SQLException ex) { Logger.getLogger(FormSiswa.class.getName()).log(Level.SEVERE, null, ex); } } void kosongkanTeks() { txtNis.setText(""); txtNama.setText(""); txtAlamat.setText(""); } public TabelSiswa getTabelModel() { return tabelSiswa; } public void setTabelSiswa (TabelSiswa tabelSiswa) { this.tabelSiswa = tabelSiswa; } /** 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() { jLabel1 = new javax.swing.JLabel(); txtNis = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtNama = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtAlamat = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); tabelIsiData = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("NIS"); txtNis.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNisActionPerformed(evt); } }); jLabel2.setText("Nama"); jLabel3.setText("Alamat"); tabelIsiData.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(tabelIsiData); jButton1.setText("Tambah"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Ubah"); 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(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(txtAlamat) .addComponent(txtNama) .addComponent(txtNis, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)) .addContainerGap(27, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(txtNis, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3)

.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(jButton1) .addComponent(jButton2) .addComponent(jButton3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold> private void txtNisActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: if (!txtNis.getText().isEmpty() && !txtNama.getText().isEmpty() && !txtAlamat.getText().isEmpty()) { try { // TODO add your handling code here: daoMysql.connect(); Siswa sisw = new Siswa(); sisw.setNis(txtNis.getText()); sisw.setNama(txtNama.getText()); sisw.setAlamat(txtAlamat.getText()); daoMysql.insert(sisw); loadData(); } catch (SQLException ex) { Logger.getLogger(FormSiswa.class.getName()).log(Level.SEVERE, null, ex); } } else { JOptionPane.showMessageDialog(null, "Harus diisi semua", "Salah", JOptionPane.ERROR_MESSAGE); } this.kosongkanTeks(); // TODO add your handling code here: } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { try {

// TODO add your handling code here: daoMysql.connect(); int index = tabelIsiData.getSelectedRow(); if (jButton2.getText().equals("Ubah")) { records = daoMysql.read(); Siswa siswa = records.get(index); String nis = siswa.getNis(); Siswa newSiswa = daoMysql.read(nis); txtNis.setText(newSiswa.getNis()); txtNama.setText(newSiswa.getNama()); txtAlamat.setText(newSiswa.getAlamat()); jButton2.setText("Simpan"); } else { Siswa newSiswa = new Siswa(); newSiswa.setNis(txtNis.getText()); newSiswa.setNama(txtNama.getText()); newSiswa.setAlamat(txtAlamat.getText()); if (JOptionPane.showConfirmDialog(this, "apakah anda yakin untuk melakukan update", "konfirmasi update", JOptionPane.OK_CANCEL_OPTION) == 0) { daoMysql.update(records.get(index).getNis(), newSiswa); loadData(); this.kosongkanTeks(); jButton2.setText("Update"); JOptionPane.showMessageDialog(this, "Data berhasil di update"); } } daoMysql.disconnect(); } catch (SQLException ex) { Logger.getLogger(FormSiswa.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: int index = tabelIsiData.getSelectedRow(); if (JOptionPane.showConfirmDialog(this, "apakah anda yakin untuk menghapus data", "konfirmasi penghapusan", JOptionPane.OK_CANCEL_OPTION) == 0) { try { daoMysql.connect(); records = daoMysql.read(); daoMysql.delete(records.get(index).getNis()); JOptionPane.showMessageDialog(this, "data berhasil di hapus"); } catch (SQLException ex) { Logger.getLogger(FormSiswa.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "data belum dipilh", "error", JOptionPane.ERROR_MESSAGE); }

} loadData(); // TODO add your handling code here: } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FormSiswa().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 tabelIsiData; private javax.swing.JTextField txtAlamat; private javax.swing.JTextField txtNama; private javax.swing.JTextField txtNis; // End of variables declaration } setelah itu kita buat class TableSiswa.java untuk mengurusi table yang ada di view /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package lat1.objek.model; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import lat1.objek.entity.Siswa; /** * * @author acusgazerock */ public class TabelSiswa extends AbstractTableModel { List<Siswa> list = new ArrayList<Siswa>();

public TabelSiswa(List list) { this.list=list; }

public int getRowCount() { return this.list.size(); } public int getColumnCount() { return 3; } public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return list.get(rowIndex).getNis(); case 1: return list.get(rowIndex).getNama(); case 2: return list.get(rowIndex).getAlamat(); default: return null; } } @Override public String getColumnName(int column) { switch (column) { case 0: return "Nis"; case 1: return "Nama"; case 2: return "Alamat"; default: return null; } } }

Berikut hasil akhir tampilan nya :