Connect to PostgreSQL with JDBC driver

Here is an example to show you how to connect to PostgreSQL database with JDBC driver.

1. Download PostgreSQL JDBC Driver

Get a PostgreSQL JDBC driver at this URL : http://jdbc.postgresql.org/download.html

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 : JDBCExample.java

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

public class JDBCExample {

	public static void main(String[] argv) {

		System.out.println("-------- PostgreSQL "
				+ "JDBC Connection Testing ------------");

		try {

			Class.forName("org.postgresql.Driver");

		} catch (ClassNotFoundException e) {

			System.out.println("Where is your PostgreSQL JDBC Driver? "
					+ "Include in your library path!");
			e.printStackTrace();
			return;

		}

		System.out.println("PostgreSQL JDBC Driver Registered!");

		Connection connection = null;

		try {

			connection = DriverManager.getConnection(
					"jdbc:postgresql://127.0.0.1:5432/testdb", "mkyong",
					"123456");

		} catch (SQLException e) {

			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return;

		}

		if (connection != null) {
			System.out.println("You made it, take control your database now!");
		} else {
			System.out.println("Failed to make connection!");
		}
	}

}

3. Run it

Assume JDBCExample is store in c:\test folder, together with PostgreSQL JDBC driver, then run it :


C:\test>java -cp c:\test\postgresql-8.3-603.jdbc4.jar;c:\test JDBCExample
-------- MySQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
You made it, take control your database now!

Done

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
mutaz
Guest
mutaz

when i run it using the cmd it gives the following error:
could not find or load main class for JDBCExample
and when i use JCreator to run it, it gives the following error:
Usage: java [-options] class [args…]
(to execute a class)
or java [-options] -jar jarfile [args…]
(to execute a jar file)…
…………………..

Mina
Guest
Mina

Thanks!

Sebastian Cheung
Guest
Sebastian Cheung

Have added postgreSQL JDBC driver, and also in PostGreSQL.app running in the background and createdb mkyong, but it is still reporting error of:

org.postgresql.util.PSQLException: FATAL: role “mkyong” does not exist

at org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:691)

at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:207)

at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)

at org.postgresql.jdbc2.AbstractJdbc2Connection.(AbstractJdbc2Connection.java:156)

at org.postgresql.jdbc3.AbstractJdbc3Connection.(AbstractJdbc3Connection.java:35)

at org.postgresql.jdbc3g.AbstractJdbc3gConnection.(AbstractJdbc3gConnection.java:22)

at org.postgresql.jdbc4.AbstractJdbc4Connection.(AbstractJdbc4Connection.java:47)

at org.postgresql.jdbc4.Jdbc4Connection.(Jdbc4Connection.java:30)

at org.postgresql.Driver.makeConnection(Driver.java:414)

at org.postgresql.Driver.connect(Driver.java:282)

at java.sql.DriverManager.getConnection(DriverManager.java:664)

at java.sql.DriverManager.getConnection(DriverManager.java:247)

at JDBCExample.main(JDBCExample.java:31)

Sid
Guest
Sid

Please add PostgreSQL JDBC Driver in your Classpath

how to get solution for this??

Sid
Guest
Sid

Please add PostgreSQL JDBC Driver in your Classpath

how to solve this?/

Sid
Guest
Sid

Please add PostgreSQL JDBC Driver in your Classpath

Sid
Guest
Sid

how to give -cp in ubuntu….????

Bakasa Barato Kawaii#loliTim
Guest
Bakasa Barato Kawaii#loliTim

Thanks men, your info help me more than another pages.

Dinesh
Guest
Dinesh

Excellent Work .. thanks much.. Keep up..

Khan
Guest
Khan

Anyone help me! I cannot query some data from table.

I have a table named FOO in PostgrelSQL. In java I qurey: select * from FOO. Then it make error “ERROR: relation “FOO” does not exist”. Sorry for my English

Nophawit Karunlanchakorn
Guest
Nophawit Karunlanchakorn

thank to much for your article.

cuong le
Guest
cuong le

Hi Mkyong. I’m building web service java using server tomcat and apache axis 2. But when i connect to postgresql database, so it has an error: “java.lang.NoClassDefFoundError: org/postgresql/Driver” although i have built path jdbc postgresql library.
Could you tell me an advise to solve this error.
Thanks you so much!

Asiana
Guest
Asiana

Thank you so much. This is a very quick and easy tutorial. Thank you :)

Karl
Guest
Karl
This is possibly the best guide for connecting to Postgresql with JDBC. If I can suggest a few things before this tutorial begins, a few lines on the setup within postgresql itself that are needed first but not obvious how to do them. I will also include how I did each step, but I did it a crude way — sorry! -create user with password (I created the user, then altered it to add a password) -create database with user access (I created the database with owner = user) -configure postgresql to allow user access through the localhost (I edited… Read more »
Edison QuisiguiƱa
Guest
Edison QuisiguiƱa

Muchas Gracias, Bendiciones :)
Thanks a lot, Blessings on you :)

Alexander
Guest
Alexander

Thanks!

Joshua
Guest
Joshua

Mr mkyong, I have an android app that will connect to the Postgresql and when i try your code it says that my jdbc driver is registered but when i connect it to the postgre database, it can’t connect ..why?? Please help
im using eclipse. Is it about the connection?

Asem
Guest
Asem

thank you very much!

Luke
Guest
Luke

Nice and simple explaination, thanks!

Kamran
Guest
Kamran

Awesome. Thanks! Plain and simple, unlike all the other Spring tutorials out there! Please carry on the great work sir! :)

Ahmedou
Guest
Ahmedou

Thank a lot

Matthias
Guest
Matthias

Great description how to connect to a postgre-database using JDBC!

Mike
Guest
Mike

I found JdbcTemplate from Spring (e.g. here http://www.dzone.com/tutorials/java/spring/spring-jdbc-tutorial-1.html) less bulky

Mike
Guest
Mike
Roberta
Guest
Roberta

It was really helpful! Thank you a lot!

Saga Castro
Guest
Saga Castro
Hi. Thanks, your site has helped me quite a lot (Just stating with Java). Now I’m trying yo connect to a remote DB located in my school’s server that i usually connect through putty’s SSH/Ubuntu 12.04 and I have the task of connecting to that DB from a java program. I have this code import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class JDBCExample { public static void main(String[] argv) { System.out.println("-------- PostgreSQL " + "JDBC Connection Testing ------------"); try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); return; } System.out.println("PostgreSQL JDBC Driver Registered!"); Connection connection = null; try { connection… Read more »
Will
Guest
Will

Hope you have solved it but the problem is your JDBC isn’t located at the specified path or you have downloaded the JDBC driver.

Will
Guest
Will

Also, it says “.driver” it should be “.JDBC”

Innocent
Guest
Innocent

NB:
I use the default database provided by the software. it is called: DREBY. openbravo pos version is 2.30.2.
or knowing anything java or linux I prefer to entrust an expert like you.
I’ve entered data into the database. if you agree I will pass. thank you

Innocent
Guest
Innocent
A Mr. Kyong. First of all, congratulations for the work you do. I would like to request your assistance to modify a software point of sale pos openbarvo call. I’d like to make a few changes to adapt to my commercce. I am convinced that you know you should do it. The changes I want are: – Turn the A5 ticket (because I use a laser printer hp 1020) – Make a statement of my profits over – Change the state of my products (enlarge the column name products, drop the column taxes) and finally to another state with just… Read more »
ravi mandali
Guest
ravi mandali

hi..
i am use netbeans 7.2
and my database cannectin is pgadmin of postgresql..
i have ready classes for the database….
so how can i direct make table in pgadmin by using of persistance classes…??

plzz sir rpl me…

ARUMUGAM
Guest
ARUMUGAM

Dear Sir,

I am using openjdk 1.6, netbeans 6.5.1(having postgres8.3 jdbc driver), postgres8.4 on centOS6.0.

pg_hba.conf is having an entry
host all all 127.0.0.1/32 md5

postmaster (pid 1466) is running…

also added port 5432 protocol tcp to permit by SELinux.

I am getting error

“Unable to add connection. Cannot establish connection to jdbc:postgresql://127.0.0.1:5432/postgres using org.postgresql.Driver(connection refused.Check that the host name and port name are correct and that the postmaster is accepting TCP/IP connections”)

Please help me!

Thanks and Regards

abu
Guest
abu

Can you solve it?
What was the problem?

Vito
Guest
Vito

Check that the host name and port name are correct and that the postmaster is accepting TCP/IP connections

Murad
Guest
Murad

Thank you. it works