Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Error connecting to Postgresql via JDBC!!! PLEASE HELP, POINTS AWARDED!!

Posted on 2006-11-14
Medium Priority
Last Modified: 2008-01-09
Its bin a while since i have post an issue,:). Neways back to the problem. I have been trying to connect to my database in Postgresql via using JDBC. However i am finding it difficult:

>>I have installed the JDBC drivers and have a java code which simply tries to connect to the database.
>>Once connected the program should show that task was completed, however i get the following response after compiling and trying to run the java file.

Note "//" comments!

C:\>java HelloPostgresql postgres postgres ****** // this is password to database!
java.lang.ClassNotFoundException: org.postgresql.Driver
java.lang.ClassNotFoundException: org.postgresql.Driver
        at$ Source)
        at Method)
        at 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.ClassLoader.loadClassInternal(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at HelloPostgresql.<init>(
        at HelloPostgresql.main(

The Java file Postgresql is as follows:

import java.sql.*;   // All we need for JDBC
import java.text.*;

public class HelloPostgresql
  Connection       db;        // A connection to the database
  Statement        sql;       // Our statement to run queries with
  DatabaseMetaData dbmd;      // This is basically info the driver delivers
                              // about the DB it just connected to. I use
                              // it to get the DB version to confirm the
                              // connection in this example.

  public HelloPostgresql(String argv[])
    throws ClassNotFoundException, SQLException
    String database = argv[0];
    String username = argv[1];
    String password = argv[2];
    Class.forName("org.postgresql.Driver"); //load the driver
    db = DriverManager.getConnection("jdbc:postgresql:"+database,
                                     password); //connect to the db
    dbmd = db.getMetaData(); //get MetaData to confirm connection
    System.out.println("Connection to "+dbmd.getDatabaseProductName()+" "+
                       dbmd.getDatabaseProductVersion()+" successful.\n");
    sql = db.createStatement(); //create a statement that we can use later

    String sqlText = "create table jdbc_demo (code int, text varchar(20))";
    System.out.println("Executing this command: "+sqlText+"\n");

    sqlText = "insert into jdbc_demo values (1,'One')";
    System.out.println("Executing this command: "+sqlText+"\n");

    sqlText = "insert into jdbc_demo values (3,'Four')";
    System.out.println("Executing this command twice: "+sqlText+"\n");

    sqlText = "update jdbc_demo set text = 'Three' where code = 3";
    System.out.println("Executing this command: "+sqlText+"\n");
    System.out.println (sql.getUpdateCount()+
                        " rows were update by this statement\n");

    System.out.println("\n\nNow demostrating a prepared statement...");
    sqlText = "insert into jdbc_demo values (?,?)";
    System.out.println("The Statement looks like this: "+sqlText+"\n");
    System.out.println("Looping three times filling in the fields...\n");
    PreparedStatement ps = db.prepareStatement(sqlText);
    for (int i=10;i<13;i++)
      ps.setInt(1,i);         //set column one (code) to i
      ps.setString(2,"HiHo"); //Column two gets a string

    System.out.println("Now executing the command: "+
                       "select * from jdbc_demo");
    ResultSet results = sql.executeQuery("select * from jdbc_demo");
    if (results != null)
      while (
        System.out.println("code = "+results.getInt("code")+
                           "; text = "+results.getString(2)+"\n");

    sqlText = "drop table jdbc_demo";
    System.out.println("Executing this command: "+sqlText+"\n");


  public static void correctUsage()
    System.out.println("\nIncorrect number of arguments.\nUsage:\n "+
                       "java   \n");

  public static void main (String args[])
    if (args.length != 3) correctUsage();
      HelloPostgresql demo = new HelloPostgresql(args);
    catch (Exception ex)

Thanks for the help in advance, will view replies at 12pm tomorrow.

Thanks Again Experts!!

Question by:deepanp
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
LVL 62

Accepted Solution

gheist earned 500 total points
ID: 17944819
You have to add jdbc jar file somewhere in classpath...
LVL 22

Assisted Solution

by:earth man2
earth man2 earned 500 total points
ID: 17945528
I don't know what your database url has been input as but it needs to include host and port eg.
If you specify CLASSPATH then you need to include the current directory - to find HelloPostgresql.class

db = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"+database,

java  -cp .:$JAVA_HOME/jre/lib/ext/postgresql.jar HelloPostgresql mydbname myusername mypassword
Connection to PostgreSQL 8.2beta2 successful.

Executing this command: create table jdbc_demo (code int, text varchar(20))

Executing this command: insert into jdbc_demo values (1,'One')

Executing this command twice: insert into jdbc_demo values (3,'Four')

Executing this command: update jdbc_demo set text = 'Three' where code = 3

2 rows were update by this statement

Now demostrating a prepared statement...
The Statement looks like this: insert into jdbc_demo values (?,?)

Looping three times filling in the fields...




Now executing the command: select * from jdbc_demo
code = 1; text = One

code = 3; text = Three

code = 3; text = Three

code = 10; text = HiHo

code = 11; text = HiHo

code = 12; text = HiHo

Executing this command: drop table jdbc_demo
LVL 22

Expert Comment

by:earth man2
ID: 17945732
Though if you're running on same machine where the database is at and are using the default port then the url specified will work just fine.
Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.


Author Comment

ID: 17946995
yes i am only using the same machine for the database, and the port details are set to default. The classpath was added into the system as well with the jar jdbc. thanks earthman2, i will have a go and post the result in a few minutes.

Thanks again for the help!
LVL 22

Expert Comment

by:earth man2
ID: 17947117
To make the code portable between databases specify complete url  and omit the line
Class.forName("org.postgresql.Driver"); //load the driver

add command line option -Djdbc.Drivers

java -Djdbc.Drivers=org.postgresql.Driver  -cp .:$JAVA_HOME/jre/lib/ext/postgresql.jar HelloPostgresql jdbc:postgresql://localhost:5432/mydbname myusername mypassword

Author Comment

ID: 17948762

I tried to execute the code with the line

 db = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"+database,

but there was no luck.

Let me show my settings for the classpaths, following:

SYSTEM CLASSPATH: C:\Program Files\Java\jre1.5.0_06\lib\ext\;C:\Program Files\PostgreSQL\8.1\jdbc\postgresql-8.1-405.jdbc3.jar
JAVAHOME: C:\Program Files\Java\jdk1.5.0_06
QTJAVA: C:\Program Files\Java\jre1.5.0_06\lib\ext\
VARIABLE CLASSPATH.;.;.;C:\PROGRA~1\JMF21~1.1E\lib\sound.jar;C:\PROGRA~1\JMF21~1.1E\lib\jmf.jar;C:\PROGRA~1\JMF21~1.1E\lib;C:\Program Files\PostgreSQL\8.1\jdbc\postgresql-8.1-405.jdbc3

I Hope this helps.
The java file is located: C:/

Thanks, will keep trying now

Author Comment

ID: 17949107

This is a link where i got a step by step set up from. hope this helps for all that is helping out.

Thanks again!

Author Comment

ID: 17949793
Hey GUYS.. I would like to thank all the help that you have given.. however it was infact a CLASSPATH problem.. To Future reviews with the same problem, I would like to say that i had Tomcat 4.1 installed. The problem was that the CLASSPATH has to point to the file where the lib folder of the JDK folder is. i.e. C:\Program Files\Java\jdk1.5.0_06\lib\postgresql-8.1-407.jdbc3.jar. and you also have to include the same class path in the user variables.

This is what made it work for me..

Thanks again..

Althought not much help was given, i will still award points, however equally in this instance.

Thanks Experts!!

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Best database to use for Maps is PostgreSQL. This is an open source database. Comes as a package with most Linux OS. For more info visit the following site: ( This requires some add-o…
Many developers have database experience, but are new to PostgreSQL. It has some truly inspiring capabilities. I have several years' experience with Microsoft's SQL Server. When I began working with MySQL, I wanted a quick-reference to MySQL (htt…
Steps to create a PostgreSQL RDS instance in the Amazon cloud. We will cover some of the default settings and show how to connect to the instance once it is up and running.
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question