Minggu, 18 September 2011

Mengakses Database

Untuk mengakses database dengan Java cukup mudah. API Java yang perlu dipelajari ada dalam paket java.sql. Class-class yang berhubungan dengan mengakses database antara lain Connection, Statement, PreparedStatement dan ResultSet. Teknologi Java untuk mengakses database disebut JDBC. Dengan JDBC kita dapat menciptakan koneksi ke database, mengirimkan perintah-perintah sql dan memproses hasil eksekusi sql.

Hal lain yang dibutuhkan untuk mengakses database adalah JDBC Driver. JDBC Driver berbeda untuk setiap database yang ada. Misalnya JDBC Driver untuk MySQL akan berbeda dengan JDBC Driver untuk SQL Server atau Oracle.

Aplikasi database yang dikembangkan menggunakan teknologi Java tidak akan terikat dengan database yang digunakan. Maksudnya adalah kita dapat bergonta-ganti database engine dari yang satu ke database engine yang lain tanpa harus mengubah source program kita secara signifikan. Yang perlu diganti hanyalah JDBC Driver yang digunakan.

Berikut adalah beberapa contoh program Java sederhana untuk mengakses database MySQL. Sekali lagi untuk mengakses database MySQL dibutuhkan JDBC Driver MySQL. Silahkan download di sini

Membaca Data
/**
* @author Hendro Steven
*/
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.*;
public class DatabaseApp{
public static void main(String args[]){
 Connection conn = null;
 Statement st = null;
 ResultSet result=null;

 String sql = "SELECT * FROM t_pegawai";

 try{
   //load Driver
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   //Define the Connection URL
   String dbURL = "jdbc:mysql://localhost/db_training";
   String dbUser = "";
   String dbPass = "";
   //Establish The Connection
   conn = DriverManager.getConnection(dbURL,dbUser,dbPass);
   //Create a statement object
   st = conn.createStatement();
   //Execute a query
   result = st.executeQuery(sql);
   //Process the results
   System.out.println("Database Result :");
   while(result.next()){
     String kode = result.getString(1);
     String nama = result.getString(2);
     String alamat = result.getString(3);
     String gaji = result.getString(4);
     System.out.println("KODE   : "+ kode);
     System.out.println("NAMA   : "+ nama);
     System.out.println("ALAMAT : "+ alamat);
     System.out.println("GAJI   : "+ gaji);
     System.out.println();
   }   
   //close the connection
   st.close();
   conn.close();   
 }catch (InstantiationException e) {
   System.out.println("InstantiationException....");
   System.out.println(e.getMessage());
 }catch (ClassNotFoundException e) {
   System.out.println("ClassNotFoundException....");
   System.out.println(e.getMessage());
 }catch (IllegalAccessException e) {
   System.out.println("IllegalAccessException....");
   System.out.println(e.getMessage());
 }catch (SQLException e) {
   System.out.println("SQLException....");
   System.out.println(e.getMessage());
 }
}
}

Menambah Data
/**
* @author Hendro Steven SalatigaCamp
*/
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;

public class AddDataApp{
public static void main(String args[]){
  Connection conn = null;
  Statement st = null;
  ResultSet result=null;

  String sql = "";
  BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

  try{
    //load Driver
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    //Define the Connection URL
    String dbURL = "jdbc:mysql://localhost/db_training";
    String dbUser = "";
    String dbPass = "";
    //Establish The Connection
    conn = DriverManager.getConnection(dbURL,dbUser,dbPass);
    //Create a statement object
    st = conn.createStatement();
  
    //ambil input dari console
    System.out.println("Input Data");
    System.out.print("KODE     : "); String kode = input.readLine();
    System.out.print("NAMA   : "); String nama = input.readLine();
    System.out.print("ALAMAT : "); String alamat = input.readLine();
    System.out.print("GAJI   :");  double gaji = Double.parseDouble(input.readLine());    
    sql = "INSERT INTO t_pegawai VALUES('"+kode+"','"+nama+"','"+alamat+"',"+gaji+")";
  
    //Execute a query
    st.executeUpdate(sql);
    System.out.println("Completed...");
  
    //close the connection
    st.close();
    conn.close();
  }catch (InstantiationException e) {
    System.out.println("InstantiationException....");
    System.out.println(e.getMessage());
  }catch (ClassNotFoundException e) {
    System.out.println("ClassNotFoundException....");
    System.out.println(e.getMessage());
  }catch (IllegalAccessException e) {
    System.out.println("IllegalAccessException....");
    System.out.println(e.getMessage());
  }catch (SQLException e) {
    System.out.println("SQLException....");
    System.out.println(e.getMessage());
  }catch (IOException e){
    System.out.println("IOException....");
    System.out.println(e.getMessage());
  }           
}
}

Menghapus Data
/**
 * @author Hendro Steven SalatigaCamp
 */
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;

public class DelDataApp{
 public static void main(String args[]){
   Connection conn = null;
   Statement st = null;
   ResultSet result=null;
  
   String sql = "";
   BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  
   try{
     //load Driver
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     //Define the Connection URL
     String dbURL = "jdbc:mysql://localhost/db_training";
     String dbUser = "";
     String dbPass = "";
     //Establish The Connection
     conn = DriverManager.getConnection(dbURL,dbUser,dbPass);
     //Create a statement object
     st = conn.createStatement();
    
     //ambil input dari console
     System.out.println("Input Kode Yang akan dihapus :");
     System.out.print("KODE     : "); String kode = input.readLine();       
     sql = "DELETE FROM t_pegawai WHERE kode='"+kode+"'";
    
     //Execute a query
     st.executeUpdate(sql);
     System.out.println("Completed...");
    
     //close the connection
     st.close();
     conn.close();
   }catch (InstantiationException e) {
     System.out.println("InstantiationException....");
     System.out.println(e.getMessage());
   }catch (ClassNotFoundException e) {
     System.out.println("ClassNotFoundException....");
     System.out.println(e.getMessage());
   }catch (IllegalAccessException e) {
     System.out.println("IllegalAccessException....");
     System.out.println(e.getMessage());
   }catch (SQLException e) {
     System.out.println("SQLException....");
     System.out.println(e.getMessage());
   }catch (IOException e){
     System.out.println("IOException....");
     System.out.println(e.getMessage());
   }            
 }
}

Tidak ada komentar:

Posting Komentar