Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres JDBC connection in Eclipse Help

I'm trying to get a postgres jdbc connection working in eclipse. It would be nice to use the Data Source Explorer, but for now I'm just trying to get a basic connection. What I have done so far is download the postgres JDBC connector. I then tried two different things. First, Preferences-> Data Management, I tried to add the postgres connector. Second, I added the jar to my project and tried to load the driver using Class.forName("org.postgresql.Driver"); but neither worked. Does anyone have any ideas?

Thanks, Charlie

like image 1000
Charlie White Avatar asked Oct 14 '08 02:10

Charlie White


2 Answers

This is how I have made a connection: (I do not know if this is "best practice", but it works.)

Importing the driver:

  1. Right click on your project
  2. Choose property
  3. Choose Java build path
  4. Choose Add external JARS.. and select the location to the JDBC driver.

Here is my code:

try{
    Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException cnfe){
      System.out.println("Could not find the JDBC driver!");
      System.exit(1);
    }
Connection conn = null;
try {
    conn = DriverManager.getConnection
                   (String url, String user, String password);
     } catch (SQLException sqle) {
       System.out.println("Could not connect");
       System.exit(1);
     }

The url can be of one of the following formats:

jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
like image 103
eflles Avatar answered Oct 13 '22 12:10

eflles


I was also having this problem as well and Vjeux's answer helped point me in the right direction.

I have a local copy of Tomcat6 that was installed and is managed by Eclipse. It was installed into '$HOME/bin/tomcat6'. To get the PostgreSQL JDBC driver working I simply copied my postgresql.jar file into the '$HOME/bin/tomcat6/lib' directory.

Also, if you don't know where to get the driver from in the first place, try this. I'm running Ubuntu so I ran 'sudo apt-get install libpg-java' which installed the driver into '/usr/share/java/postgresql.jar' and so I just copied it from there.

like image 43
Jamie Carl Avatar answered Oct 13 '22 11:10

Jamie Carl