0

I am trying to build my first PostgreSQL database in java. The way I like to learn is to take some code, get it to work and then modify it to develop my understanding.

I have loaded postgreSQL on my win10 laptop and I am trying to get the code below to run:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;


public class PostgreSQLJDBC {
   public static void main( String args[] ) {
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql://localhost:5432/testdb",
            "manisha", "123");
         System.out.println("Opened database successfully");

         stmt = c.createStatement();
         String sql = "CREATE TABLE COMPANY " +
            "(ID INT PRIMARY KEY     NOT NULL," +
            " NAME           TEXT    NOT NULL, " +
            " AGE            INT     NOT NULL, " +
            " ADDRESS        CHAR(50), " +
            " SALARY         REAL)";
         stmt.executeUpdate(sql);
         stmt.close();
         c.close();
      } catch ( Exception e ) {
         System.err.println( e.getClass().getName()+": "+ e.getMessage() );
         System.exit(0);
      }
      System.out.println("Table created successfully");
   }
}

When I run the above code I am getting an error

Java.lang.ClassNotFoundException: org.postgresql.Driver

Can anyone please help me understand what is happening and what I need to do to remove this error. I am new to Java - self learning - so my apologies in advance if this is basic.

Berti
  • 51
  • 3
  • 2
    Does this answer your question? [java.lang.ClassNotFoundException: org.postgresql.Driver, Android](https://stackoverflow.com/questions/10903481/java-lang-classnotfoundexception-org-postgresql-driver-android) Answer ther says that you need to add the postgresql driver to your program class path. How to do it is a different case and depends on how do you compile and run your program. – itwasntme Feb 29 '20 at 14:54
  • 1
    have you added the postgresql api to your project? here is a link to a download https://jdbc.postgresql.org/download.html – fuggerjaki61 Feb 29 '20 at 14:57
  • thank you - now loaded the Jar file and making progress.... – Berti Feb 29 '20 at 15:03
  • Please add post and accept your own Answer to mark this Question resolved. Or delete your Question if it holds no value for others. – Basil Bourque Feb 29 '20 at 15:57
  • 1
    Tips: You’ll want to learn about try-with-resources syntax. And you’ll want to learn about the non-pooled implementation of `DataSource` built into the Postgres JDBC driver. – Basil Bourque Feb 29 '20 at 16:00

0 Answers0