Monday, November 21, 2005

PostgreSQL on Mac OS X

PostgreSQL on Mac OS X:

import java.sql.*;
import java.text.*;
import java.io.*;

public class PgTest
{
Connection db; // connection object
Statement sql; // statement to run queries with

// the constructor does all the work in this simple example

public PgTest(String argv[])
throws ClassNotFoundException, SQLException
{
String database = argv[0];
String username = argv[1];
String password = argv[2];

// load the JDBC driver for PostgreSQL
Class.forName("org.postgresql.Driver");

// connect to the datbase server over TCP/IP
// (requires that you edit pg_hba.conf
// as shown in the "Authentication" section of this article)
db = DriverManager.getConnection("jdbc:postgresql:"+database,
username,
password);

// create a statement for later use
sql = db.createStatement();

String theQuery = "select name from foo order by foo_id";
System.out.println("Now executing query: \""+ theQuery + "\"\n");

ResultSet results = sql.executeQuery(theQuery);
if (results != null)
{
while (results.next())
{
System.out.println("Name: "+results.getString("name")+"\n");
}
}
else
{
System.out.println("No rows found");
}
results.close();

db.close();
}

public static void showUsage()
{
System.out.println("\nUsage:\n "+
"java PgTest \n");
System.exit(1);
}

public static void main (String args[])
{
if (args.length != 3) showUsage();
try
{
PgTest showMe = new PgTest(args);
}
catch (Exception ex)
{
System.out.println("Caught Exception:\n"+ex);
ex.printStackTrace();
}
}
}

0 Comments:

Post a Comment

<< Home