Listing 3. JDBC Example

import java.sql.*;
public class PostgresJdbc {
  final static String loginUser = "peter";
  final static String loginPasswd = "";
  final static String loginUrl =
    "jdbc:postgresql:dbname";
  final static String loginJdbc =
    "postgresql.Driver";
  public static void main( String [] args ) {
  if( args.length > 0 ) {
  try {
  Class.forName( loginJdbc );
  Connection con = DriverManager.getConnection(
    loginUrl, loginUser, loginPasswd );
  Statement stmt = con.createStatement();
  ResultSet rs = stmt.executeQuery( args[0] );
  ResultSetMetaData rsmd = rs.getMetaData();
  int colCount = rsmd.getColumnCount();
  for( int j = 1; j < colCount; j++ )
  System.out.print( rsmd.getColumnName(j)+",");
  System.out.println( rsmd.getColumnName(
    colCount ));
  while( rs.next()) {
  for( int k = 1; k < colCount; ++k )
  System.out.print( rs.getString( k ) + ",");
  System.out.println( rs.getString( colCount ));
  }
  }
  catch( Exception e ) {
  e.printStackTrace();
  }
  }
  else
  System.out.println(
"Usage: java PostgresJdbc \"...SQL...\"" );
  }
}