Java Sample
Cut and paste this program into your favorite text editor, save it as "JavaSample.java", compile and run it. It has been tested with Java 1.4, but should work with any version above 1.1. Before compiling or running, set the classpath to include the location of the Postgres JDBC Client class. For example:
set CLASSPATH=c:\postgres\jdbc\pg73jdbc3.jar;.\
// This trivial sample will select first 15 cities with the greatest number of medical examiners.
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
class JavaSample
{
public JavaSample() throws SQLException
{
Connection conn;
Statement stmt;
ResultSet rs;
int limit = 0;
StringBuffer lineBuffer = new StringBuffer(50);
String sql =
"Select city, state, count(*) " +
"from medical_examiners " +
"group by city, state " +
"order by 3 desc, 1 ";
// Load the JDBC driver
DriverManager.registerDriver(new org.postgresql.Driver());
// Connect to the database. Replace "yourid" and "yourpassword" with your userid and password. The rest of
// the parameters will not change.
conn = DriverManager.getConnection ("jdbc:postgresql://aviationdb.net/aviation","yourid", "yourpassword");
// Create a Statement
stmt = conn.createStatement ();
// prepare and execute the statement
rs = stmt.executeQuery(sql);
// format a heading line
lineBuffer.setLength(50);
lineBuffer.insert(0, "City");
lineBuffer.insert(30, "State");
lineBuffer.insert(50, "Count");
String line = new String(lineBuffer);
System.out.println(line.trim());
//Get all the rows
while (rs.next ())
{
// get each of the returned columns and create a formatted line
lineBuffer.setLength(0);
lineBuffer.setLength(50);
lineBuffer.insert(0, rs.getString (1));
lineBuffer.insert(30, rs.getString (2));
lineBuffer.insert(50, rs.getString (3));
line = new String(lineBuffer);
System.out.println(line.trim());
limit++;
if (limit == 15)
break;
}
// Close the ResultSet
rs.close();
// Close the Statement
stmt.close();
// Close the connection
conn.close();
}
public static void main (String args [])
{
System.out.println("JavaSample started at " + new Date() + "\r\n");
try
{
JavaSample js = new JavaSample();
}
catch (SQLException e)
{
e.printStackTrace();
}
System.out.println("\r\nJavaSample ended at " + new Date());
}
}
| Legal |
Copyright 2001 - 2008 AviationDB.com Corp. All Rights Reserved |
Contact Us |