Figure 2
JdbcTest1 java program
package com.web400.mysql.jdbc;
import java.sql.*;
import java.text.*;
import java.util.*;
/**
* Test MySQL JDBC driver
*/
public class JdbcTest1 {
public static void main(java.lang.String[] args) {
final int EXIT_ERROR = 1;
//********************************************************
// A: initialize the JDBC driver class
//********************************************************
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException cnfe) {
System.err.println("ClassNotFoundException for " + cnfe.getMessage());
cnfe.printStackTrace();
System.exit(EXIT_ERROR);
}
//********************************************************
// B: driver initialized, prepare/run SQL
//********************************************************
try {
//Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/World");
Connection conn =
DriverManager.getConnection("jdbc:mysql://WXP/World?user=cpelkie&password=cpelkie");
Statement stmt = conn.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT CODE, NAME, SURFACEAREA, POPULATION FROM COUNTRY ORDER BY POPULATION DESC");
//****************************************************
// C: display column headings
//****************************************************
System.out.println("Count/Code/Name/SurfaceArea/Population");
//****************************************************
// D: iterate over the result set
//****************************************************
int i = 0;
while (rs.next()) {
++i;
StringBuffer sb = new StringBuffer();
sb.append(i).append(" ");
sb.append(rs.getString("CODE").trim());
sb.append("/");
sb.append(rs.getString("NAME").trim());
sb.append("/");
sb.append(rs.getInt("SURFACEAREA"));
sb.append("/");
sb.append(rs.getInt("POPULATION"));
System.out.println(sb);
}
rs.close();
stmt.close();
conn.close();
}
//********************************************************
// E: catch SQLException
//********************************************************
catch (SQLException sqle) {
System.err.println("An SQL exception occurred:");
do {
System.err.println("Message: " + sqle.getMessage());
System.err.println("SQLState: " + sqle.getSQLState());
System.err.println("ErrorCode: " + sqle.getErrorCode());
} while (sqle.getNextException() != null);
}
//********************************************************
// F: catch generic exception
//********************************************************
catch (Exception e) {
System.err.println("Exception occurred: " + e.getMessage());
e.printStackTrace();
}
System.out.println("** Done **");
}
}