How To Connect to PostgreSQL with a JDBC driver
This is example will show you how to connect to PostgreSQL database via a JDBC driver.
First, download the PostgreSQL JDBC driver.
To run this code, your need to put "postgresql-{version}-bin.jar" in classpath.
JDBCPostgreSQLExample.java
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.vertex.academy.databases; //STEP 1. Import required packages import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class JDBCPostgreSQLExample { // Database credentials static final String DB_URL = "jdbc:postgresql://127.0.0.1:5432/vertex" static final String USER = "username"; static final String PASS = "password"; public static void main(String[] argv) { System.out.println("Testing connection to PostgreSQL JDBC"); try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.out.println("PostgreSQL JDBC Driver is not found. Include it in your library path "); e.printStackTrace(); return; } System.out.println("PostgreSQL JDBC Driver successfully connected"); Connection connection = null; try { connection = DriverManager .getConnection(DB_URL, USER, PASS); } catch (SQLException e) { System.out.println("Connection Failed"); e.printStackTrace(); return; } if (connection != null) { System.out.println("You successfully connected to database now"); } else { System.out.println("Failed to make connection to database"); } } } |
To run this code, you have to put JDBCPostgreSQLExample.java in the same folder as the PostgreSQL JDBC driver. For example, you can put it in "c:\test," and then execute:
C:\test>java -cp c:\test\postgresql-8.3-603.jdbc4.jar;c:\test JDBCPostgreSQLExample.java
You should then see something like this:
1 2 3 |
Testing connection to PostgreSQL JDBC PostgreSQL JDBC Driver connected You successfully connected to database now |