Please send questions to
st10@humboldt.edu .
// modified from [CIS 318] Lab6.java, written by Ann Burroughs
//
// ask users to tell you which column of the emp
// table they want, then build a query with that
// column and display it
//
// modified by: Sharon Tuttle
// last modified: 4-16-01
import java.sql.*;
import java.io.*;
public class AskForCol
{
public static void main(String args[])
{
Statement myStmt;
ResultSet myRS;
String response, myQ, rowToPrint;
BufferedReader in;
int colCode = 0;
String[] colNames = {"empno", "ename", "job", "mgr",
"hiredate", "sal", "comm", "deptno"};
try
{
// load JDBC driver and set up db connection
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@redwood:1521:student",
"java", "java");
// declare and create a statement object
myStmt = con.createStatement();
// this local method prints a list of
// column choices for the user
printColChoices();
System.out.println("");
// ask the user which column they wish to see
System.out.println("Type the integer of a " +
"desired column: ");
System.out.flush();
in = new BufferedReader(new InputStreamReader(
System.in));
response = in.readLine();
response = response.trim(); // trim white space
try
{
// subtract 1 because array indices are 0-7
colCode = Integer.parseInt(response) - 1;
if ((colCode < 0) || (colCode > 7))
{
System.out.println("AskForCols: " +
"column out of range --- not" +
" between 1-8: " + response);
myStmt.close();
con.close();
System.exit(0);
}
}
catch(NumberFormatException exc)
{
System.out.println("AskForCols: bad " +
"column --- not between 1-8: " +
response);
myStmt.close();
con.close();
System.exit(0);
}
// whew! I have a good column, at this point
myQ = "select " + colNames[colCode] +
" from emp";
myRS = myStmt.executeQuery(myQ);
System.out.println(colNames[colCode]);
System.out.println("-----------------------");
while (myRS.next() != false)
{
// hmm --- what does this do to non-strings?
// (seems mostly reasonable, but note that
// you get the string "null" for a null
// value...!
rowToPrint = myRS.getString(colNames[colCode]);
System.out.println(rowToPrint);
}
System.out.println("-----------------------");
// close statement and connection!
myStmt.close();
con.close();
}
catch (Exception exc)
{
System.out.println("AskForCol: " + exc.getMessage());
}
}
// this simply prints out a "menu" of column
// choices for the user to choose from
private static void printColChoices()
{
System.out.println("------------------------------");
System.out.println("Choose which column you wish:");
System.out.println("------------------------------");
System.out.println("1. empno");
System.out.println("2. ename");
System.out.println("3. job");
System.out.println("4. mgr");
System.out.println("5. hiredate");
System.out.println("6. sal");
System.out.println("7. comm");
System.out.println("8. deptno");
System.out.println("------------------------------");
}
}