package controller;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @about : class untuk koneksi ke database MySQL dengan JDBC
*/
public class DatabaseConnection {
private Connection con = null;
private static DatabaseConnection dbcon = null;
static final String DB_URL = "jdbc:mysql://localhost:3306/latihan";
static final String DB_USER = "root";
static final String DB_PASS = "";
// constructor
public DatabaseConnection() {
if (con == null) {
try {
// loading driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// connect ke database
con = (Connection) DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
System.out.println("Koneksi Berhasil");
} catch (Exception ex) {
System.out.println("Koneksi Gagal");
}
}
}
// mengecek apakah sudah ada koneksi
public static DatabaseConnection getInstance() {
DatabaseConnection con = null;
if (dbcon == null) {
dbcon = new DatabaseConnection();
con = dbcon;
} else {
con = dbcon;
}
return con;
}
public Connection getCon() throws SQLException {
return this.con;
}
}
Sekarang kita bisa panggil class tersebut pada class lain, contohnya buat java class dengan nama TesConnection, berikut contoh source codenya:
selamat mencoba....
package controller;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @about : coba koneksi
*/
public class TestConnection {
public static void main(String[] args) {
DatabaseConnection koneksi = DatabaseConnection.getInstance();
try {
Connection con = koneksi.getCon();
} catch (SQLException ex) {
Logger.getLogger(TestConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
selamat mencoba....
0 comments
Post a Comment