Using JDBC with PostgreSQL – Tutorial and Example

The purpose of this tutorial is to write and test the first JDBC driver programs to connect PostgreSQL and manipulate the data stored in the PostgreSQL database.

Quick View PostgreSQL JDBC Driver.

PostgreSQL JDBC driver allows Java programs to connect to a PostgreSQL database using standard, database independent Java code. its current version is 9.1-901. It supports both JDBC3 and JDBC4 standard implementation(If you are using 1.6 or 1.7 JVM, Advice you use JDBC4 Postgresql Driver, Version 9.1-901).

Download PostgreSQL JDBC Driver.

You can download the driver from the site: http://jdbc.postgresql.org/download.html, please check the min-requirement of JDBC driver if you are not clear. the binary download JAR file of the JDBC driver are available on above link, please add the Jar to Java classpath prior to starting code.

Code Tutorial and Example to connect PostgreSQL via Java JDBC.

The DriverManager class take over the management of the establishment of Connections, we have to import java.sql.DriverManager and register PostgreSQL JDBC implementation class org.postgresql.Driver, the following is the code tutorial and example:

 package com.asjava;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class PostgreSQLJDBCDriverTest {
	public static void main(String[] argv) throws InstantiationException, IllegalAccessException {
		Connection conn = null;
		try {
		    Class.forName("org.postgresql.Driver").newInstance();
		    System.out.println("postgresql JDBC Driver Registered!");

		    conn = DriverManager.getConnection(
					"jdbc:postgresql://localhost:5432/testdb", "asjava",
					"123");
		    //Or use this way
		    conn = DriverManager.getConnection("jdbc:postgresql://localhost/localhost:5432?" +
            "user=asjava&password=123");
		    //Do something with the Connection
		} catch (ClassNotFoundException e) {
		    //Cannot register postgresql MySQL driver
			System.out.println("This is something you have not add in postgresql library to classpath!");
		    e.printStackTrace();
		}catch (SQLException ex) {
		    // handle any errors
		    System.out.println("SQLException: " + ex.getMessage());
		    System.out.println("SQLState: " + ex.getSQLState());
		    System.out.println("VendorError: " + ex.getErrorCode());
		}finally{
		    //After using connection, release the postgresql resource.
		    try {
				conn.close();
			} catch (SQLException e) {
			}
		}
	}
}

Once a connection is established, you can start something with the PostgreSQL connection like creating Statement and PreparedStatement objects.

JDBC MySQL PostgreSQL Connection String.

Two ways to get PostgreSQL connection via JDBC driver

  1. conn = DriverManager.getConnection(“jdbc:postgresql://localhost:5432/testdb”, “asjava”,”123″);
  2. conn = DriverManager.getConnection(“jdbc:postgresql://localhost/localhost:5432?user=asjava&password=123″);

The way 1 is to pass three parameters into getConnection method, the second and third parameters are username and password.

The way 2 is to concatenate all db connection info including host, db name, user name and password into a single connection string.

Rate article
ASJAVA.COM
Add a comment

Your email address will not be published. Required fields are marked *

  1. gatto

    wow, incredible. need more exciting tutorials!

    Reply
  2. Casey Kemp

    I have verified the PostgreSQL jar files are in my classpath and copied the Java code, and successfully compiled it.

    C:\Documents and Settings\ckemp>echo %CLASSPATH%
    C:\Program Files\Java\jdk1.7.0_45\lib;C:\Program Files\Java\jdk1.7.0_45\bin;C:\Program Files\PostgreSQL\pgJDBC

    nonetheless, having created the PostgreSQL database and schema, I still get the following error and my question is why?

    C:\AZ_Fantasy5>java -cp . PostgreSQLJDBCDriverTest
    This is something you have not add in postgresql library to classpath!
    java.lang.ClassNotFoundException: org.postgresql.Driver
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at PostgreSQLJDBCDriverTest.main(PostgreSQLJDBCDriverTest.java:24)
    Exception in thread “main” java.lang.NullPointerException
    at PostgreSQLJDBCDriverTest.main(PostgreSQLJDBCDriverTest.java:46)

    Reply