Sunday, February 2, 2014

Contoh Aplikasi Mysql & Java

Berikut ini saya berikan contoh program Pemrograman Berorientasi Obyek II Database yang digunakan adalah akademik, tabel mahasiswa dan server adalah localhost. Gunakan class KoneksiMysql.

import java.sql.*;
import java.io.*;

class menu {
public static void main(String args[]) throws IOException{
BufferedReader stdin=new
BufferedReader(new InputStreamReader(System.in));

String buff;
int pilih; 

try { 
 KoneksiMysql kon = new KoneksiMysql ("akademik");
 Connection c = kon.getConnection();
 pilih=0;
  while(pilih<5) {
 System.out.println(" Menu : ");
 System.out.println(" 1. Lihat Data ");
 System.out.println(" 2. Tambah Data ");
 System.out.println(" 3. Hapus Data ");
 System.out.println(" 4. Update Data ");
 System.out.println(" 5. Exit ");
 System.out.print(" Pilih nomor : ");
 buff = stdin.readLine();
 pilih=Integer.parseInt(buff);
 ResultSet hasilQuery = null;
    Statement stm = connection.createStatement();

 switch(pilih){
  case 1:
  {
        hasilQuery = stm.executeQuery("SELECT * FROM mahasiswa");  

    while (hasilQuery.next()) {
            String nim_mahasiswa = hasilQuery.getString("nim");
        String nama_mahasiswa =  hasilQuery.getString("nama");
        System.out.println(nim_mahasiswa+" -> " + nama_mahasiswa); }
            
   break;
  }
  case 2:
  {
   String nim_t, nama_t;
   System.out.print("nim     : ");
   nim_t = stdin.readLine();
   System.out.print("nama    : ");
   nama_t = stdin.readLine();
       String sql="INSERT into mahasiswa values('"+nim_t+"','"+nama_t+"')";  
              stm.executeUpdate(sql);  
   break;
  }
  case 3:
  {
   String nim_h;
   System.out.print("nim     : ");
   nim_h = stdin.readLine();
         String sqlh="DELETE from mahasiswa where nim = '"+nim_h+"'";  
             stm.executeUpdate(sqlh);  
   break;
  }
  case 4:
  {
   String nim_u,nama_u;
   System.out.print("nim     : ");
   nim_u = stdin.readLine();
hasilQuery = stm.executeQuery("SELECT * FROM mahasiswa where nim = '" + nim_u + "'");  
   while (hasilQuery.next()) {
    String nm_mahasiswa =  hasilQuery.getString("nama");
    System.out.println("Nama : " + nm_mahasiswa); 
   }

   System.out.print("Nama Baru  : ");
   nama_u = stdin.readLine();

String sqlu="UPDATE mahasiswa set nama='" + nama_u + "' where nim = '" + nim_u + "'";  
            stm.executeUpdate(sqlu);  
   break;
   } 
  default:
   {
   System.out.println("Bye");
   break; }
    
  }
  }
 connection.close();
      
 } 
    catch (Exception e) {
  System.out.println("Error : "+e);
  }
  }
}
Post a Comment