Logo java |
1. Buat database dengan nama bebas, namu sebagai contoh saya gunakan nama “coba_database_konsole”. Kemudian buat tabel dengan nama “mahasiswa” seperti berikut:
kemudian tambahkan beberapa data ke tabel tersebut.
2. Buat project di netbeans kemudian klik kanan libraries di navigator project yang ada di sebelah kiri, klik “Add Library”
3. Pilih “MySQL JDBC Driver”
4. Fuat file koneksi.java untuk membuat koneksi ke database
package coba_database_konsole; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * * @author CYBER_WOLF */ public class koneksi { private String dbuser = "root"; private String dbpasswd = ""; private String dbname="jdbc:mysql://localhost/coba_database_konsole"; private Statement stmt = null; private Connection con = null; private ResultSet rs = null; public koneksi() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { System.out.println("JDBC Driver Eror"); } try { con = DriverManager.getConnection(dbname, dbuser, dbpasswd); stmt = con.createStatement(); } catch (Exception e) { System.out.println("Connection Error 1"); } } public ResultSet getData(String SQLString) { try { rs = stmt.executeQuery(SQLString); } catch (Exception e) { System.out.println("Communication Error 2"); } return rs; } public void query(String SQLString) { try { stmt.executeUpdate(SQLString); } catch (Exception e) { System.out.println("Communication Error 3"); } } } |
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package coba_database_konsole; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author CYBER_WOLF */ public class mahasiswa { private koneksi k = new koneksi(); private String nim, nama, s; private int i = 0; private ResultSet rs; public mahasiswa(){ } public mahasiswa(String nim, String nama) { this.nim = nim; this.nama = nama; } public void setNama(String nama) { this.nama = nama; } public void setNim(String nim) { this.nim = nim; } public void insert() { s = "insert into mahasiswa value('" + this.nim + "','" + this.nama + "')"; k.query(s); } public void update() { rs = null; s = "update mahasiswa set nama='"+nama+"' where nim='"+nim+"'"; k.query(s); } public int cekMahasiswa() { s = "select * from mahasiswa where nim='" + nim + "'"; rs = k.getData(s); i = 0; try { while (rs.next()) { i++; } } catch (SQLException ex) { System.out.println("Terjadi SQL Exception"); } return i; } public void delete() { s = "delete from mahasiswa where nim='" + nim + "'"; k.query(s); } public ResultSet view() { s = "select * from mahasiswa"; rs = k.getData(s); return rs; } public int isEmpty(){ s = "select * from mahasiswa"; rs = k.getData(s); i = 0; try { while (rs.next()) { i++; } } catch (SQLException ex) { System.out.println("Terjadi SQL Exception"); } return i; } } |
Berikan Komentar tentang Artikel Ini