JDBC koneksi ke Ms.Access 2007

Koneksi database Java (JDBC) ke database Ms.Access 2007 menggunakan class sun.jdbc.odbc.JdbcOdbcDriver, dimana file diletakan database Ms.Access diletakan dalam direktori aplikasi.

Berikut kode programnya

package com.rojulman.db

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;

/**
 *
 * @author rojulman
 */
public class DBKoneksi {

    private Connection con;
    // membuat path
    private String path_db;
    public DBKoneksi() {
    path_db=new java.io.File("").getPath();
    initDB();
 }
 public void initDB()
 {
     path_db= path_db + "latihan.accdb";
 try
 {

 String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="
                          + path_db;
 /* Ms.Access 2000 ( *.mdb )
 String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="
  + path_db; */
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 con = DriverManager.getConnection(url,"","");
 }catch (Exception ee)
 {
 System.out.println("path error" + path_db);
 System.out.println("GAGAL KONEKSI DATABASE");
 ee.printStackTrace();
 }
 }

 public Connection getKoneksi()
 {
        //path_db=new java.io.File("").getPath();
 try
 {
 if (this.con != null || this.con.isClosed())
 {
 this.initDB();
 }
 }catch(SQLException ee)
 {
 ee.printStackTrace();

 }
 return this.con;
 }

 public void closeKoneksi()
 {
 try
 {
 if (this.con != null) this.con.close();
 }catch(SQLException ee)
 {
 System.out.println("GAGAL TUTUP KONEKSI");
 ee.printStackTrace();
 }
    }
}

Contoh Pengunaannya pada class TesSelect :

package com.rojulman;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author rojulman
 */
public class TesSelect {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        String sql = "SELECT * FROM jenis_produk";

        DBKoneksi dbkon = new DBKoneksi();
      try
      {
        Statement st = dbkon.getKoneksi().
                createStatement();
        ResultSet rs = st.executeQuery(sql);

        while(rs.next())
        {
          System.out.println(rs.getInt("idjenis")
                  + " - " + rs.getString("nama")
                  )  ;

        }
        dbkon.closeKoneksi();
        }catch (SQLException ee)
      {
            System.out.println("UPPS ERROR ");
            ee.printStackTrace();
        }
    }

}

Post a Response