Kelas mahasiswa bisa dibuat setelah ada file JMySQL untuk koneksi ke database.
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* @author a3m-nix
*/
public class mahasiswa{
private String nim;
private String nama;
private String alamat;
public String getNim(){
return nim;
}
public void setNim(String nim){
this.nim = nim;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public void simpan(){
JMySQL.cn = JMySQL.getKoneksi();
try {
JMySQL.pr = JMySQL.cn.prepareStatement("insert into "
+ "mahasiswa values (?,?,?)");
JMySQL.pr.setString(1, this.getNim());
JMySQL.pr.setString(2, this.getNama());
JMySQL.pr.setString(3, this.getAlamat());
JMySQL.pr.executeUpdate();
} catch (SQLException er) {
JOptionPane.showMessageDialog(null, "Data Gagal disimpan, error "+er);
return;
}
JOptionPane.showMessageDialog(null, "Data sudah disimpan");
JMySQL.tutupKoneksi(JMySQL.cn, JMySQL.pr, JMySQL.rs);
}
public void hapus(){
JMySQL.cn = JMySQL.getKoneksi();
try {
JMySQL.pr = JMySQL.cn.prepareStatement("delete from mahasiswa where nim=?");
JMySQL.pr.setString(1, this.getNim());
JMySQL.pr.executeUpdate();
}catch (SQLException e){
JOptionPane.showMessageDialog(null, "Gagal Menghapus Data, Error "+e);
return;
}
JMySQL.tutupKoneksi(JMySQL.cn, JMySQL.pr, JMySQL.rs);
JOptionPane.showMessageDialog(null, "Data sudah dihapus");
}
public void ubah(){
JMySQL.cn = JMySQL.getKoneksi();
try {
JMySQL.pr = JMySQL.cn.prepareStatement("update mahasiswa set nama=?,"
+ "alamat=? where nim=?");
JMySQL.pr.setString(1, this.getNama());
JMySQL.pr.setString(2, this.getAlamat());
JMySQL.pr.setString(3, this.getNim());
JMySQL.pr.executeUpdate();
}catch (SQLException e){
JOptionPane.showMessageDialog(null, "Data gagal diubah, Error "+e);
return;
}
JMySQL.tutupKoneksi(JMySQL.cn, JMySQL.pr, JMySQL.rs);
JOptionPane.showMessageDialog(null, "Data sudah diubah");
}
public void tampil(JTable tblData,String kondisi){
JMySQL.cn = JMySQL.getKoneksi();
JMySQL.tblMode = (DefaultTableModel) tblData.getModel();
JMySQL.tblMode.getDataVector().removeAllElements();
if(!kondisi.equals("")){
kondisi = " where "+kondisi;
}
try{
JMySQL.pr = JMySQL.cn.prepareStatement("select *from mahasiswa "+kondisi);
JMySQL.pr.executeQuery();
JMySQL.rs = JMySQL.pr.getResultSet();
while(JMySQL.rs.next()){
this.nim = JMySQL.rs.getString("nim");
this.nama = JMySQL.rs.getString("nama");
this.alamat = JMySQL.rs.getString("alamat");
JMySQL.tblMode.addRow(new Object[]{this.nim,this.nama,this.alamat});
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
JMySQL.tutupKoneksi(JMySQL.cn, JMySQL.pr, JMySQL.rs);
}
}
0 Komentar