Saturday, May 18, 2013

Finally .... The Authentication Issue Resolved for Connecting to PostGreSQL from Java

Hooh! So HAPPY!!! Finally, got it resolved for PostgreSQL 9.2 in Windows Environment

Inside the pg_hba.conf that is inside the folder C:\Program Files\PostGreSQL\9.2\data, navigate to the section titled "# IPv4 ...", and add this:


# IPv4 local connections:
host    all             all             0.0.0.0/0                trust
host    all             all             127.0.0.1/32            trust

For the second row, which is originally there with md5 authentication, make it trust also.

This solution is referenced to: http://www.postgresql.org/docs/9.2/static/auth-methods.html

For more details about any security issue, if your scenario is not for localhost connection. For my case, am trying to connect using localhost.

The following is a sample code used in Java:


import java.sql.*;
import java.util.*;

public class PGSample
{
  public static void main(String[] args)
  {
    Connection connection = null;
    try
    {
      // the postgresql driver string
      Class.forName("org.postgresql.Driver");
 
      // the postgresql url
      String url = "jdbc:postgresql://localhost:5432/TestDB";
   
      // get the postgresql database connection
      connection = DriverManager.getConnection(url,"pguser", "");
   
      // now do whatever you want to do with the connection
      // ...
   
    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
      System.exit(1);
    }
    catch (SQLException e)
    {
      e.printStackTrace();
      System.exit(2);
    }
  }
}

Note: Replace the database TestDB with the name of the DB in your pc or server. Also, replace "pguser" with the user id in your own server.

Converting a Physical Linux to Virtual

Hmm ... I have done a lot of work on my Linux Lubuntu 15.10 with PHP and PostgreSQL and a few other things ... it is quite time-consuming to...