import java.sql.*;

// This appears in Core Web Programming from
// Prentice Hall Publishers, and may be freely used
// or adapted. 1997 Marty Hall, hall@apl.jhu.edu.

/** A test connecting to and printing a very simple
 *  database. You must use Java 1.1 and obtain and
 *  install the Connect Software driver for this to work.
 */

public class TestDB {
  public static void main(String[] args) {
    // Use driver from Connect SW
    String driver = "connect.microsoft.MicrosoftDriver";
    try {
      Class.forName(driver);
      String url =
        "jdbc:ff-microsoft://" + // FastForward 
        "dbtest.apl.jhu.edu:1433/" + // Host:port
        "pubs"; // Database name
      String user = "sa", password="";
      // Establish connection
      Connection connection =
        DriverManager.getConnection(url, user, password);
      // Create a statement
      Statement statement = connection.createStatement();
      // Define query
      String query =
        "SELECT col1, col2, col3 FROM testDB";
      // Execute query and save results
      ResultSet results =
        statement.executeQuery(query);
      // Print column names
      String divider =   "-----+------+-----";
      System.out.println("Col1 | Col2 | Col3\n" +
                         divider);
      // Print results
      while(results.next())
        System.out.println
          (pad(results.getString(1), 4) + " | " +
           pad(results.getString(2), 4) + " | " +
           results.getString(3) + "\n" +
           divider);
      // If driver class not found
    } catch(ClassNotFoundException cnfe) {
      System.out.println("No such class: " + driver);
      // If other connection/query error
    } catch(SQLException se) {
      System.out.println("SQLException: " + se);
    }
  }

  /** Pad a string with enough spaces to take up
   *  designated size. Assumes original string is
   *  shorter than this originally.
   */
  
  private static String pad(String val, int spaces) {
    val = " " + val;
    while(val.length() < spaces)
      val = val + " ";
    return(val);
  }
}

