
JDBC is a core API of Java 1.1 and later. It provides a standard set of interfaces to SQL-compliant databases.
PostgreSQL provides a type 4 JDBC driver. Type 4 indicates that the driver is written in Pure Java, and communicates in the database system’s own network protocol. Because of this, the driver is platform independent; once compiled, the driver can be used on any system. sumber: wiki postgreSQL
Oke kita mulai JDBC PostgreSQL dengan Java
1). Download JDBC PostgreSQL disini.
2). Buka editor eclipse kita, buat project java dengan nama “Belajar JDBC PostgreSQL”
3). Create folder “lib”, lalu copy jar JDBC PostgreSQL ke folder “lib”, kemudian jar JDBC PostgreSQL add to “Build Path”
4). Buat Class dengan nama “PostgreSQLJDBC” jangan lupa saat create class centang “static void main”
5). Tambahkan variabel “connection” dengan getter setternya dan tambahkan contructornya, seperti coding dibawah ini:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private Connection connection; public PostgreSQLJDBC() { } public Connection getConnection() { if (connection == null) createConnection(); return connection; } public void setConnection(Connection connection) { this.connection = connection; } |
6). Tambahkan metod “createConnection”, metod ini digunakan untuk meregister driver postgresql dan menginisialisasi variabel connection. berikut cuplikan codingnya:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public void createConnection() { System.out.println("----- Inisialisai PostgreSQL JDBC -----"); try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.out.println("Driver tidak ketemu..."); e.printStackTrace(); } System.out.println("Driver terpasang!"); connection = null; try { connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/wijaksana", "wijaksana", "wijaksana"); connection.setAutoCommit(false); } catch (SQLException e) { System.out.println("Koneksi DB gagal!"); e.printStackTrace(); } if (connection != null) { System.out.println("Koneksi DB Sukses!"); } else { System.out.println("Koneksi DB gagal!"); } System.out.println("----- Inisialisasi selesai -----"); } |
connection = DriverManager.getConnection(“jdbc:postgresql://127.0.0.1:5432/wijaksana“, “wijaksana“, “wijaksana“);
pada cuplikan coding diatas tulisan “wijaksana” cetak tebal adalah “Nama Database“, “Username“, “Password”
7). Untuk memanggil/testing tambahkan coding di metod main seperti dibawah ini:
1 2 3 4 |
public static void main(String[] args) { PostgreSQLJDBC sql = new PostgreSQLJDBC(); sql.createConnection(); } |
8). Outputnya:
—– Inisialisai PostgreSQL JDBC —–
Driver terpasang!
Koneksi DB Sukses!
—– Inisialisasi selesai —–
Semoga Membantu,
Salam berbagi,
Yulianto Wijaksana