Re: Basic JDBC - Mailing list pgsql-novice

From Steve Waldman
Subject Re: Basic JDBC
Date
Msg-id 20001118033156.A21247@peanut-butter.mchange.com
Whole thread Raw
In response to Basic JDBC  (Christian Hemmingsen <hemmingsen@kampsax.dtu.dk>)
List pgsql-novice
Christian,

You work with postgresql from JDBC the same way you work
with any other database. There is nothing in the code that
is postgresql specific, other than using the postgres jdbc
driver class and an appropriate postgres jdbc url.

Here is a code snippet. Hope it helps, and good luck.

    smiles,
       Steve

---

  [ in some class that imports java.sql.* ]

  public static void main(String[] args)
  {
     try
     {
        // load the JDBC driver
        // (perhaps more flexibly, one could leave this
        //  out and use the System property jdbc.drivers
        //  to load the driver)
        // the driver (jar file) needs to be in your classpath!

        Class.forName("org.postgresql.Driver");

        //get a Connection to the postgres database called test
        //on localhost, with postgres' default port. you need
        //to have started postmaster with the '-i' flag so that
        //it accepts network connections. the username you supply
        //has to be a real postgres user, and the connection should
        //come from an authorized host, defined in pg_hba.conf

        Connection con = DriverManager.getConnection("jdbc:postgresql://localhost/test", "swaldman", "mypassword");

        //usual JDBC stuff

        //make a Statement, a reusable pipeline through which you
        //send a single SQL statement at a time

        Statement stmt = con.createStatement();

        //use the Statement to execute a query and get a hold of
        //a ResultSet

        ResultSet rs = stmt.executeQuery("SELECT color, size FROM bicycle");

        //Iterate through the rows of the ResultSet, and do
        //what you like with the contents

        while (rs.next())
        {
           //Note: SQL things are indexed from 1, not 0
           //      like Java arrays and collections

           System.out.println( "Color: " + rs.getString(1) );
           System.out.println( "Size: "  + rs.getString(2) );
           System.out.println();
        }

        //THESE SHOULD BE IN A FINALLY BLOCK. REALLY!!!

        stmt.close(); //should automatically close ResultSet
        con.close();
     }
     catch (Exception e)
     { e.printStackTrace(); }
  }


On Fri, Nov 17, 2000 at 07:28:45PM +0100, Christian Hemmingsen wrote:
> Hi
> Is there some kind of introduction or tutorial on using the postgresql JDBC drivers? If
> not, could anyone post a snippet of code on how to connect to postgresql?
>
> Thanks
> Christian Hemmingsen

pgsql-novice by date:

Previous
From: "Lars Therkelsen"
Date:
Subject: Global Unique Identifier
Next
From: Mike White
Date:
Subject: Icons for Postgresql