JDBC dengan ResourceBundle Properties
Koneksi ke database dengan JDBC dapat menggunakan file properties untuk menyimpan konfigurasi akses database ( user , password, nama database dan server database), misal file properties ini bernama db.properties dan letakan file ini dalam hirarki project pada direktori SRC.
Berikut contoh isi file db.properties
dbuser=rojul dbpass=passrojul dbhost=localhost dbname=latihan
Berikut contoh class DBKoneksi ( JDBC ke database MySQL) yang menggunakan ResourceBundle Properties :
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.rojulman.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ResourceBundle; /** * * @author rojulman */ public class DBKoneksi { private Connection con ; ResourceBundle bundle = null; public DBKoneksi() { bundle = ResourceBundle.getBundle("db"); initDB(); } public void initDB() { String dbuser = bundle.getString("dbuser"); String dbpass = bundle.getString("dbpass"); String dbname = bundle.getString("dbname"); String dbhost = bundle.getString("dbhost"); try { String url = "jdbc:mysql://"+dbhost+":3306/"+dbname; Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url,dbuser,dbpass); }catch (Exception ee) { System.out.println("GAGAL KONEKSI DATABASE"); ee.printStackTrace(); } } public Connection getKoneksi() { 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(); } } }