Re: Basic JDBC

From: Steve Waldman <swaldman(at)mchange(dot)com>
To: Christian Hemmingsen <hemmingsen(at)kampsax(dot)dtu(dot)dk>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Basic JDBC
Date: 2000-11-18 08:31:56
Message-ID: 20001118033156.A21247@peanut-butter.mchange.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

  • Basic JDBC at 2000-11-17 18:28:45 from Christian Hemmingsen

Browse pgsql-novice by date

  From Date Subject
Next Message Mike White 2000-11-18 15:43:30 Icons for Postgresql
Previous Message Lars Therkelsen 2000-11-17 20:56:41 Global Unique Identifier