Connect to PostgreSQL via JDBC driver
Here is an example to show you how to connect to PostgreSQL database with JDBC driver.
** UPDATE: Complete JDBC tutorial now available here.
1. Download PostgreSQL JDBC Driver
Get PostgreSQL JDBC driver here –
2. Java JDBC connection example
Code snippets to use JDBC to connect a PostgreSQL database
Class.forName("org.postgresql.Driver"); Connection connection = null; connection = DriverManager.getConnection( "jdbc:postgresql://hostname:port/dbname","username", "password"); connection.close();
See a complete example below:
File:PostgreSqlJDBC.java
package com.simplecode.jdbc; import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class PostgreSqlJDBC { private static final String DB_DRIVER = "org.postgresql.Driver"; private static final String DB_CONNECTION="jdbc:postgresql://127.0.0.1:5432/simplecodedb"; private static final String DB_USER = "username"; private static final String DB_PASSWORD = "password"; public static void main(String[] argc) { System.out.println("***** PostgreSQL JDBC Connection Testing *****"); try { Class.forName(DB_DRIVER); } catch (ClassNotFoundException e) { System.err.println("Please add PostgreSQL JDBC Driver in your Classpath "); System.err.println(e.getMessage()); return; } System.out.println("PostgreSQL JDBC Driver Registered!"); Connection connection = null; try { connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); } catch (SQLException e) { System.err.println("Connection Failed, Check console"); System.err.println(e.getMessage()); return; } if (connection == null) { System.out.println("Connection Failed !"); } else { System.out.println("Connection established!"); } } }
how to compile above code in terminal?????