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 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.ClassLoader.loadClassInternal(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at HelloPostgresql.<init>(HelloPostgresql.java:20)
        at HelloPostgresql.main(HelloPostgresql.java:102)

The Java file Postgresql is as follows:

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

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 (results.next())
        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
  • 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.
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.


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\QTJava.zip;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\QTJava.zip
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

[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

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: http://www.postgresql.org/ (http://www.postgresql.org/) This requires some add-o…
By, Vadim Tkachenko. In this article we’ll look at ClickHouse on its one year anniversary.
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.
This video tutorial shows you the steps to go through to set up what I believe to be the best email app on the android platform to read Exchange mail.  Get the app on your phone: The first step is to make sure you have the Samsung Email app on your …

599 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