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

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: parking()

  • Pingback: laan nu()

  • Pingback: stop parking()

  • Pingback: alkaline water machine()

  • Pingback: laane penge nu()

  • Pingback: mobile porn movies()

  • Pingback: check out DIRECTV channels()

  • Pingback: Julie gets caught on hidden camera()

  • Pingback: Blue Coaster33()

  • Edison Quisiguiña

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

  • Alexander

    Thanks!

  • 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

    thank you very much!

  • Luke

    Nice and simple explaination, thanks!

  • Kamran

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

  • Ahmedou

    Thank a lot

  • Matthias

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

  • Mike

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

  • Roberta

    It was really helpful! Thank you a lot!

  • 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 = DriverManager.getConnection(
    					"jdbc:postgresql://200.13.89.8:22/Proyecto_agencia_automotriz", "USER",
    					"PASSWORD");
     
    		} 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!");
    		}
    	}
     
    }
    
    When i try to run it i get the next error: (i saw the above responses but couldn't manage it to work)
    
    
     C:\Users\Sâga Macaro\Desktop\dbcon>java JDBCExample
    -------- PostgreSQL JDBC Connection Testing ------------
    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 JDBCExample.main(JDBCExample.java:14)
    
    
    I'ld like to know how can i solve it, if any1 here can tell me, Also when one of the solution adds a classpath from jdk, should it be the bin from jdk or jre works?. Thanks
    • 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

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

  • 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)…
    …………………..

  • 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

    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 my product (the reference, name, and the selling price of the products.)
    If you interested my project I am ready to listen to your suggestions.
    thank you

  • 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

    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

      Can you solve it?
      What was the problem?

  • Murad

    Thank you. it works

  • Marcia

    Thank’s!

  • Djurdjura

    Thanks for this post. Really useful.

    One item I couldn’t find yet anywhere is how would you go about detecting database connection afterwards? I mean, true database connection issues, not SQL errors.

    Thanks for replying,

    D.

  • sanjeev

    many many thanks to mkyong…its working fine…

  • Ambarish

    I can connect to the database when I use the code

    java -cp c:\test\postgresql-9.1-901.jdbc3.jar;c:\test Example1

    I modidified the classpath as

    .; c:\test\postgresql-9.1-901.jdbc3.jar;c:\test

    and then I use the command.
    java Example1

    I get the following error.

    java.lang.ClassNotFoundException: org.postgresql.Driver
            at java.net.URLClassLoader$1.run(Unknown Source)
            at java.security.AccessController.doPrivileged(N
            at java.net.URLClassLoader.findClass(Unknown Sou
            at java.lang.ClassLoader.loadClass(Unknown Sourc
            at sun.misc.Launcher$AppClassLoader.loadClass(Un
            at java.lang.ClassLoader.loadClass(Unknown Sourc
            at java.lang.Class.forName0(Native Method)
            at java.lang.Class.forName(Unknown Source)
            at Example1.main(Example1.java:10)
    • http://www.mkyong.com mkyong

      Make sure postgresql-9.1-901.jdbc3.jar is configured correctly and able to locate in your class path.

      Suppose you are in Windows environment, make sure the “PATH” variable contains value of “c:\test\postgresql-9.1-901.jdbc3.jar“.

      • Ambarish

        It still gives the error that driver not found.
        I dont know where am i doing it wrong

        • Ambarish

          Hey I followed Surinders comment given below and it worked!!!!
          thanks mkyong for ur reply

      • Yogesh

        In Ubuntu, where to set the classpath and where to copy .jar file? because i am also getting the error as ClassNotFoundException: ..for Driver

    • jiameng

      Hi, I have a same problem as yours, and finally I solved it. It does help if you only change the classpath ot the environment variable. Try this:
      1.go to your project fold in the eclipse, right click, and then choose “run as”, click “run configurations”.
      2. go to class path tab, choose “add external jar”, then choose the “postgresql-9.1-901.jdbc3.jar” you have download.
      3. run it again!

      This works for me, and I hope it will help you.

      PS: reference

      http://stackoverflow.com/questions/1052978/eclipse-java-lang-classnotfoundexception

      Finally, thanks mkyong, this is a great start tutorial for gostgis on java!

      • THX

        THX A LOT

  • Alex

    Hi, I got a warning:

    SQL exception: java.sql.SQLException: No suitable driver found for jdbc:postgresql://127.0.0.1:5432/fundb

    Please replay, my boss gonna kill me :D

    • Surendra

      set your class path variable as follow
      goto my computer-> properties->Advanced->Environment Variable

      Click New
      Variable Name=CLASSPATH
      Variable Value=C:\tomcat4\common\lib\servlet-api.jar;C:\tomcat4\common\lib\commons-lang-2.4.jar; c:\jdk1.6\bin;C:\Test\postgresql-8.3-603.jdbc4.jar;

      click Ok
      and same as do for follow window.
      click ok

      click ok.

      open cmd and type
      java JDBCExample

      • Alex

        It’s works.
        Thanks!

      • Joshua

        i still have the error class not found..where can i find the tomcat folder in the above code?
        PLEASE HELP

  • haha

    does the codes above work on eclipse?

    • http://www.mkyong.com mkyong

      Sure it works…Eclipse is just an IDE

  • Pingback: JDBC Tutorials()

  • Gaurav

    Which jre version is compatible with these code? jre1.4/1.5/1.6 which one???
    I found bad version number in .class file error.
    Please reply soon.
    Thank in advance.

  • http://www.rapidindex.net Gregg Dunkle

    Cannot concur a lot more with this, incredibly attractive article. Thanks A Lot.

  • http://- bullz

    Newbie here,

    where do i put the postgresql.jre file?

    • http://www.mkyong.com mkyong

      You can put it anywhere u want, and compile with -cp option for the classpath location. e.g

      java -cp c:\test\postgresql-8.3-603.jdbc4.jar;c:\test JDBCExample
      • http://- bullz

        thanks boss :beer:

  • http://tundra.web.id tundra

    Thank’s for the article

  • http://Javascriptconnction Ezra

    Is there a way to connect to Postgres using javascript ?

    • mkyong

      interesting topic, i’ve seen some examples in MsAccess. May i know why you want to connect database in client side? it’s just doesn’t make sense to me, unless your database is store in client side as well.

      If you really want to do it, i will suggest you use Ajax to call your code in server side to connect database in server side.

  • Ubaid Raja

    Nice work, thanx for the article.

  • http://www.geeks.ltd.uk/ software development company

    } catch (SQLException e) {
    System.out.println(“Connection Failed! Check output console”);
    e.printStackTrace();
    return;
    }

    I canvot get what this part of the code does ,do you mind explain it in more detail for me to understand

    • mkyong

      it just print any SQL exception error messages…

  • vasantha kumar
  • Rui Teixeira

    Hi!
    Your code return this line to me:
    “If you reach this line, please email me by telling how you do it?”

    I just chage the address to:
    jdbc:postgresql://192.168.0.1:6000/comecont”,”xgest”, “qwerty”

    and that return the error…
    Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

    Please reply to my email. Thanks!

    • Bobs Your Uncle

      Postgres is telling you that you are trying to connect to database that is not there or is connecting to a database you are not allowed to. Check these things…

      Posgres database is running, i.e. you have started the service and
      Does the database comecont exist?
      Does 192.168.0.1 exist?
      Does 192.168.0.1 accept requests via TCP/IP (the net) on port 6000?
      Has the firewall has accepted you as a trusted zone? (e.g. the portmaster)

    • duh

      Why don’t people “READ” error messages these days… ?