Posts tagged ‘postgresql’

Java Postgres connection sample

I had to setup Postgres on my linux box, configure and make sure it was working. Since that was the case I started the install, then wrote a very simple Java program to connect and retrieve some data from one of the database tables. The install is simple and pretty easy to google. Once your Postrgres database is up and running you should be able to connect to it. You will need a java Postgres database driver, the one I downloaded was the postgresql-9.1-901.jdbc4.jar then add the jar to your project. And finally to make sure your database is accessible from a program you can use the sample below.

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

// Simple test class to prove connection to Postgres database
public class Main
{

        public Main()
                { super(); }

        public static void main(String[] args)
        {
       
                System.out.println(” Postgres Test”);
                Connection myConn = null;
               
                try
                {
                        // The driver
                        Class.forName(“org.postgresql.Driver”);
                        System.out.println(“PostgreSQL JDBC Driver Registered!”);
               
                        myConn = DriverManager.getConnection( “jdbc:postgresql://127.0.0.1:5432/testDb”,
                                        “testUser”, “myPassword” );

                        // Connected ?
                        if (myConn != null)
                                System.out.println(“Successfully connected to Postgres Database”);
   
                        // Get data from the database
                Statement stGetCount = myConn.createStatement();
            ResultSet rs = stGetCount.executeQuery(“SELECT * from  cars”);
           
            while( rs.next() )
            {
                System.out.println(“result=” + rs.getString(1) + “,” + rs.getString(2) + “,” + rs.getString(3) );
            }
        }
        catch( Exception ex )
        {
            ex.printStackTrace();
        }
        finally
        {
                try{myConn.close();}catch(Exception IDontCare ){}
        }

        }
       
}  // EOC