Home > Java > Insert, Update & Delete on Java

Insert, Update & Delete on Java


CRUD: Create, Read, Update dan Delete merupakan salah satu hal utama dalam pembangunan sebuah aplikasi berbasis database. Pada post kali ini, saya ingin berbagi aplikasi sederhana tentang insert, update dan delete data ke sebuah tabel. Tabel ini nantinya cukup menggunakan DefaultTabelModel saja, agar lebih sederhana.

Pertama, kita membuat database di MySQL.


Create database LATIHAN_JAVA;

Kemudian membuat tabel Mahasiswa dengan 3 field (ID, NIM dan NAMA).

CREATE TABLE IF NOT EXISTS `mahasiswa` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `NIM` varchar(11) DEFAULT NULL,
 `NAMA` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`ID`),
 UNIQUE KEY `NIM` (`NIM`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=39 ;

Berikut adalah object Mahasiswa:


public class Mahasiswa {
 private Long id;
 private String nim;
 private String nama;

public Long getId() {
 return id;
 }

public void setId(Long id) {
 this.id = id;
 }

public String getNama() {
 return nama;
 }

public void setNama(String nama) {
 this.nama = nama;
 }

public String getNim() {
 return nim;
 }

public void setNim(String nim) {
 this.nim = nim;
 }

}

Lalu membuat koneksi di driver MySQL:


public class MySqlConnection {
 private static Connection connection;

public static Connection getConnection() {
 if(connection == null){
 MysqlDataSource dataSource = null;
 try{
 dataSource = new MysqlDataSource();
 dataSource.setUrl("jdbc:mysql://localhost:3306/LATIHAN_JAVA");
 dataSource.setUser("root");
 dataSource.setPassword("xxxxx");
 connection = dataSource.getConnection();
 }catch(SQLException exc){
 JOptionPane.showMessageDialog(null, exc.getMessage(), "Error Koneksi", JOptionPane.ERROR_MESSAGE);
 }
 }
 return connection;
 }
}

Hasil dari implementasinya:

 Insert New Mahasiswa:

Update Data:

Delete Data:

Download NetBeans Project.

Semoga bermanfaat….

About these ads
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,088 other followers

%d bloggers like this: