Learning Java Programming by Examples
Learning Java Programming by Examples
Reader 1
Learning Java Programming By Examples
Dr. Wanlei Zhou
Contents
LESSON 1. THE FIRST JAVA PROGRAMS
2.2. Dates
2.3. Strings
2.4. Arrays
2.5. Loops
10
10
11
11
11
3.2. Inheritance
12
13
13
4.2. Alignment
13
14
15
15
15
5.3. Fonts.
17
5.4. Colours
18
18
19
19
20
21
22
22
23
6.7. Sound
25
25
25
27
28
29
30
31
8.1. Buttons
31
32
33
33
34
35
35
36
37
38
38
39
39
40
42
44
48
49
51
53
56
57
57
58
58
59
59
62
63
64
64
64
70
71
74
c. Compile "HelloWorldApplet.java"
d. Use Netscape of IE to open the testapplet.html file. View the execution of the applet.
e. Change the output into "This is my first Java applet".
b. Create "HelloAgain.html":
<HTML>
<HEAD>
<TITLE>Another Applet</TITLE>
</HEAD>
<BODY>
<P>My second Java applet says:
<BR><APPLET CODE="HelloAgainApplet.class" WIDTH=200 HEIGHT=50>
</APPLET>
</BODY>
</HTML>
}
}
2.2. Dates
a. Create program "CreateDates.java":
import java.util.*;
import java.text.*;
class CreateDates {
public static void main(String args[]) {
Date d1 = new Date(); // the current date
System.out.println("Date 1: " + d1);
// year, month (starting 0), day
GregorianCalendar d2 = new GregorianCalendar(1999, 7, 1);
System.out.println("Date 2: " + d2.get(d2.DAY_OF_WEEK) +" "+
d2.get(d2.MONTH) +" "+ d2.get(d2.DATE) +" "+ d2.get(d2.YEAR) );
// A date string
DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL,
Locale.US);
try {
Date d3 = fmt.parse("Saturday, July 4, 1998");
2.3. Strings
a. Create program "TestString.java":
class TestString {
public static void main(String args[]) {
String str = "Now is the winter of our discontent";
String str1 = "This is another string";
String str2;
System.out.println("The string is: " + str);
System.out.println("Length of this string: "
+ str.length());
System.out.println("The character at position 5: "
+ str.charAt(5));
System.out.println("The substring from 11 to 17: "
+ str.substring(11, 17));
System.out.println("The index of the character d: "
+ str.indexOf('d'));
System.out.print("The index of the beginning of the ");
System.out.println("substring \"winter\": "
+ str.indexOf("winter"));
System.out.println("The string in upper case: "
+ str.toUpperCase());
System.out.println("String1: " + str1);
System.out.println("Same object (str and str1)? " + (str == str1));
str2 = str;
System.out.println("String2: " + str2);
System.out.println("Same object (str and str2)? " + (str == str2));
}
}
2.4. Arrays
a. Create program "ArrayTest.java":
class ArrayTest {
String[] firstNames = { "Dennis", "Grace", "Bjarne", "James" };
String[] lastNames = new String[firstNames.length];
void printNames() {
int i = 0;
System.out.println(firstNames[i]
i++;
System.out.println(firstNames[i]
i++;
System.out.println(firstNames[i]
i++;
System.out.println(firstNames[i]
}
2.5. Loops
a. Create program "NameLoop.java":
class NameLoop {
String[] firstNames = { "Dennis", "Grace", "Bjarne", "James" };
String[] lastNames = new String[firstNames.length];
void printNames() {
for (int i = 0; i < firstNames.length; i++)
System.out.println(firstNames[i] + " " + lastNames[i]);
}
public static void main (String args[]) {
ArrayTest a = new ArrayTest();
a.printNames();
System.out.println("----------");
a.lastNames[0] = "Ritchie";
a.lastNames[1] = "Hopper";
a.lastNames[2] = "Stroustrup";
a.lastNames[3] = "Gosling";
a.printNames();
}
}
10
11
3.2. Inheritance
a. Create class PrintClass.java:
class PrintClass {
int x = 0;
int y = 1;
void printMe() {
System.out.println("x is " + x + ", y is " + y);
System.out.println("I am an instance of the class " +
this.getClass().getName());
}
}
c. Compile and test the program. The problem: z is not printed out.
d. To overcome the problem: overwrite the PrintMe() method.
class PrintSubClass2 extends PrintClass {
int z = 3;
void printMe() {
12
4.2. Alignment
a. Create html file HelloAgainAlign.html:
<HTML>
<HEAD>
<TITLE>This page has an applet on it, aligned left</TITLE>
</HEAD>
<BODY>
<H2>Lesson 4: Session 2: Hello Again (Align)</H2>
13
14
15
16
17
5.3. Fonts.
a. Create applet ManyFonts.java
import java.awt.Font;
import java.awt.Graphics;
public class ManyFonts extends java.applet.Applet {
public void paint(Graphics g) {
Font f = new Font("TimesRoman", Font.PLAIN, 18);
Font fb = new Font("TimesRoman", Font.BOLD, 18);
Font fi = new Font("TimesRoman", Font.ITALIC, 18);
Font fbi = new Font("TimesRoman", Font.BOLD + Font.ITALIC, 18);
g.setFont(f);
g.drawString("This
g.setFont(fb);
g.drawString("This
g.setFont(fi);
g.drawString("This
g.setFont(fbi);
g.drawString("This
}
}
5.4. Colours
a. Create applet ColorBoxes.java:
import java.awt.Graphics;
import java.awt.Color;
public class ColorBoxes extends java.applet.Applet {
public void paint(Graphics g) {
int rval, gval, bval;
for (int j = 30; j < (getSize().height -25); j += 30)
for (int i = 5; i < (getSize().width -25); i += 30) {
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);
g.setColor(new Color(rval,gval,bval));
g.fillRect(i, j, 25, 25);
g.setColor(Color.black);
g.drawRect(i-1, j-1, 25, 25);
}
}
}
b. Create html file ColorBoxes.html:
<HTML>
<HEAD>
<TITLE>Colored Boxes</TITLE>
</HEAD>
<BODY>
<H2>Lesson 5, Session 4: Colored Boxes</H2>
<P>
<APPLET CODE="ColorBoxes.class" WIDTH=400 HEIGHT=150>
</APPLET>
<P>
<A HREF="ColorBoxes.java">The Source</A>
</BODY>
</HTML>
18
19
20
21
22
23
24
g.setColor(Color.red);
g.fillOval(x-r, y-r, r*2, r*2);
}
/** Move and bounce the circle and request a redraw.
* The timer calls this method periodically. */
public void animate() {
// Bounce if we've hit an edge.
if ((x - r + dx < 0) || (x + r + dx > bounds().width)) dx = -dx;
if ((y - r + dy < 0) || (y + r + dy > bounds().height)) dy = -dy;
// Move the circle.
x += dx; y += dy;
// Ask the browser to call our paint() method to draw the circle
// at its new position.
repaint();
}
/** Start the timer when the browser starts the applet */
public void start() { timer.start_animation(); }
/** Pause the timer when browser pauses the applet */
public void stop() { timer.pause_animation(); }
}
/** This interface for objects that can be animated by an AnimationTimer */
interface Animation { public void animate(); }
/** The thread class that periodically calls the animate() method */
class AnimationTimer extends Thread {
Animation animation; // The animation object we're serving as timer for
int delay;
// How many milliseconds between "animation frames"
public AnimationTimer(Animation animation, int delay) {
this.animation = animation;
this.delay = delay;
}
public void start_animation() {
if (isAlive()) super.resume();
else start();
}
public void pause_animation() { suspend(); }
/** Loop forever, calling animate(), and then pausing the specified time. */
public void run() {
for(;;) {
animation.animate();
try { Thread.sleep(delay); } catch (InterruptedException e) { ; }
}
}
}
b.Create html file BouncingCircle.html:
<APPLET CODE="BouncingCircle.class" WIDTH=300 HEIGHT=300></APPLET>
6.7. Sound
a. Create applet AudioLoop.java:
import java.awt.Graphics;
import java.applet.AudioClip;
public class AudioLoop extends java.applet.Applet
implements Runnable {
AudioClip bgsound;
AudioClip beep;
Thread runner;
public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stop() {
if (runner != null) {
if (bgsound != null) bgsound.stop();
runner.interrupt();
runner = null;
}
}
public void init() {
bgsound = getAudioClip(getCodeBase(),"audio/loop.au");
beep = getAudioClip(getCodeBase(), "audio/beep.au");
}
public void run() {
if (bgsound != null) bgsound.loop();
while (runner != null) {
try { Thread.sleep(5000); }
catch (InterruptedException e) { }
if (beep != null) beep.play();
}
}
public void paint(Graphics g) {
g.drawString("Playing Sounds....", 10, 10);
}
}
25
26
27
28
ends[i].x, ends[i].y);
}
// draw current line
g.setColor(Color.blue);
if (currentpoint != null)
g.drawLine(anchor.x,anchor.y,
currentpoint.x,currentpoint.y);
}
}
java.awt.Graphics;
java.awt.Color;
java.awt.Event;
java.awt.Font;
29
30
31
addline(e.getX(),e.getY());
}
// same as mouseDrag
public void mouseDragged(MouseEvent e) {
if (currline < MAXLINES) {
currentpoint = new Point(e.getX(),e.getY());
repaint();
}
}
void addline(int x,int y) {
starts[currline] = anchor;
ends[currline] = new Point(x,y);
currline++;
currentpoint = null;
anchor = null;
repaint();
}
public void paint(Graphics g) {
// Draw existing lines
for (int i = 0; i < currline; i++) {
g.drawLine(starts[i].x, starts[i].y,
ends[i].x, ends[i].y);
}
// draw current line
g.setColor(Color.blue);
if (currentpoint != null)
g.drawLine(anchor.x,anchor.y,
currentpoint.x,currentpoint.y);
}
}
c. Compile the applet in Java 1.1 and test the html file.
32
33
</BODY>
</HTML>
}
}
34
c.add("Blueberries");
c.add("Bananas");
add(c);
}
}
35
36
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
add(new Button("Six"));
}
}
37
38
39
40
41
<HTML>
<HEAD>
<TITLE>A simple popup window</TITLE>
</HEAD>
<BODY>
<H2>Lesson 9, Session 4: A simple popup window</H2>
<P>
<APPLET CODE="PopupWindow.class" WIDTH=200 HEIGHT=100>
</APPLET>
<P>
<A HREF="PopupWindow.java">The Source for Popup Window</A><BR>
<A HREF="PopupActions.java">The Source for Popup actions</A><BR>
<A HREF="BaseFrame1.java">The Source for Base Frame</A>
</BODY>
</HTML>
e. Compile the applet and class files and test the html file
42
43
g. Compile the applet and class files and test the html file
44
45
46
47
g. Compile the applet and class files and test the html file
48
49
}
}
}
An echo server
Usage: S [port]
The default port is 6789
The Server program should be run first
import java.net.*;
import java.io.*;
public class S {
public final static int DEFAULT_PORT = 6789;
public static void main (String args[]) throws IOException {
Socket client;
if (args.length != 1)
client = accept (DEFAULT_PORT);
else
client = accept (Integer.parseInt (args[0]));
try {
PrintWriter writer;
BufferedReader reader;
reader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer = new PrintWriter(new
OutputStreamWriter(client.getOutputStream()));
// read a line
String line = reader.readLine();
System.out.println("Client says: " + line);
// write a line
writer.println ("You have connected to the Very Simple Server.");
writer.flush();
50
reader.close();
writer.close();
} finally { // closing down the connection
System.out.println ("Closing");
client.close ();
}
}
static Socket accept (int port) throws IOException {
System.out.println ("Starting on port " + port);
ServerSocket server = new ServerSocket (port);
System.out.println ("Waiting");
Socket client = server.accept ();
System.out.println ("Accepted from " + client.getInetAddress ());
server.close ();
return client;
}
}
51
c. Compile both programs and test run them. Start the server first, then the client. They should be on the
local machines.
An echo server
Usage: S1 [port]
The default port is 6789
The Server program should be run first
import java.net.*;
import java.io.*;
public class S1 {
public final static int DEFAULT_PORT = 6789;
public static void main (String args[]) throws IOException {
Socket client;
if (args.length != 1)
client = accept (DEFAULT_PORT);
else
client = accept (Integer.parseInt (args[0]));
try {
PrintWriter writer;
BufferedReader reader;
reader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
writer = new PrintWriter(new
OutputStreamWriter(client.getOutputStream()));
writer.println ("You are now connected to the Simple Echo Server.");
writer.flush();
for (;;) {
// read a line
String line = reader.readLine();
// and send back ACK
writer.println("OK");
writer.flush();
System.out.println("Client says: " + line);
if (line.equals("Server Exit")) {
break;
}
}
reader.close();
52
writer.close();
} finally {
System.out.println ("Closing");
client.close ();
}
}
static Socket accept (int port) throws IOException {
System.out.println ("Starting on port " + port);
ServerSocket server = new ServerSocket (port);
System.out.println ("Waiting");
Socket client = server.accept ();
System.out.println ("Accepted from " + client.getInetAddress ());
server.close ();
return client;
}
}
import java.io.*;
import java.net.*;
public class C1 {
public static final int DEFAULT_PORT = 6789;
public static void usage() {
System.out.println("Usage: java C1 [<port>]");
System.exit(0);
}
public static void main(String[] args) {
int port = DEFAULT_PORT;
Socket s = null;
int end = 0;
// parse the port specification
if ((args.length != 0) && (args.length != 1)) usage();
if (args.length == 0) port = DEFAULT_PORT;
else {
try {
port = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
usage();
}
}
try {
PrintWriter writer;
BufferedReader reader;
BufferedReader kbd;
// create a socket to communicate to the specified host and port
//InetAddress myhost = getLocalHost();
s = new Socket("localhost", port);
// create streams for reading and writing
reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
53
c. Compile both programs and test run them. Start the server first, then the client. They should be on the
same local machines.
import java.io.*;
import java.net.*;
public class C2 {
public static final int DEFAULT_PORT = 6789;
public static void usage() {
54
55
56
}
reader.close();
writer.close();
}
catch (IOException e) {
System.err.println(e);
}
// always be sure to close the socket
finally {
try {
if (s != null) s.close();
}
catch (IOException e2) { }
}
}
}
c. Compile both programs and test run them. The InetExample.java program displays the information of
any Internet host. The C2.java program can run with the S1.java program of the previous section. You
may start the S1.java program on any Internet host, then the C2.java program on any Internet host as well.
The two programs can communicate with each other.
An echo server
Usage: S3 [port]
The default port is 6789
The Server program should be run first
import java.net.*;
import java.io.*;
public class S3 extends Thread {
public final static int DEFAULT_PORT = 6789;
private Socket client = null;
public S3(Socket inSock) {
super("echoServer");
client = inSock;
}
public void run() {
Socket cSock = client;
PrintWriter writer;
BufferedReader reader;
try {
String line;
System.out.println ("Accepted from " + cSock.getInetAddress());
reader = new BufferedReader(new
InputStreamReader(cSock.getInputStream()));
writer = new PrintWriter(new
OutputStreamWriter(cSock.getOutputStream()));
writer.println ("You are now connected to the Simple Echo Server.");
writer.flush();
for (;;) {
// read a line
line = reader.readLine();
// and send back ACK
writer.println("OK");
writer.flush();
57
b. Compile the program and test run it together with the C2.java program of the previous section. Start the
server S3.java first, then the client C2.java. They can run in different machines. You can start a number of
C2.java programs on many host, communicating with the server simultaneously.
58
b. Compile the program and run it. Check the database to see if the table is created.
59
try {
con = DriverManager.getConnection(url, "admin", "admin");
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
b. Compile the program and run it. Check the database to see if the table is created.
b. Compile the program and run it. Check the database to see if the table is created.
60
b. Compile the program and run it. Check the database to see if the table is populated.
c. Create Java program InsertProduct.java:
import java.sql.*;
public class InsertProduct {
public static void main(String args[]) {
String url = "jdbc:odbc:dbtest";
Connection con;
Statement stmt;
String query = "select * from PRODUCT";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
61
}
try {
con = DriverManager.getConnection(url, "admin", "admin");
stmt = con.createStatement();
stmt.executeUpdate("insert into PRODUCT " +
"values('TV', 'Philip, 68cm, flat screen', 'T0010',
1200.00, 10)");
stmt.executeUpdate("insert into PRODUCT " +
"values('VCR', 'Sony, Mid-Drive', 'V100', 500.00, 15)");
stmt.executeUpdate("insert into PRODUCT " +
"values('TV', 'Tohisba, 34cm, remote control', 'T0012',
300.00, 20)");
stmt.executeUpdate("insert into PRODUCT " +
"values('PC', 'Dell, 256M RAM, 10GHD, 17\" monitor',
'P0012', 2400.00, 12)");
ResultSet rs = stmt.executeQuery(query);
System.out.println("P_NAME P_DESC P_CODE
P_UNIT_PRICE
P_STOCK");
while (rs.next()) {
String s = rs.getString("P_NAME");
String s1 = rs.getString("P_DESC");
String s2 = rs.getString("P_CODE");
float f = rs.getFloat("P_UNIT_PRICE");
int i = rs.getInt("P_STOCK");
System.out.println(s + " " + s1 + " " + s2 +
" " + f + " " + i);
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
d. Compile the program and run it. Check the database to see if the table is populated.
e. Create Java program InsertTransaction.java:
import java.sql.*;
public class InsertTransaction {
public static void main(String args[]) {
String url = "jdbc:odbc:dbtest";
Connection con;
Statement stmt;
String query = "select * from TRANSACTION";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "admin", "admin");
stmt = con.createStatement();
stmt.executeUpdate("insert into TRANSACTION " +
"values(500, 100, 'T0010', 1, 1200.00, #1/8/2000#)");
62
d. Compile the program and run it. Check the database to see if the table is populated.
63
System.out.print(columnValue);
}
System.out.println("");
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
}
}
b. Compile the program and run it. Check the database to see if the table is printed properly.
c. Create Java programs to print the columns of the PRODUCT and the TRANSACTION tables.
64
b. Compile the program and run it. Check the database to see if the result is selected properly.
java.awt.*;
java.awt.event.*;
java.applet.Applet;
java.io.*;
65
b. Create the Java program that implements the ClientComm class used in the applet:
ClientComm.java. This program deals with the major communication work between the applet and the
server.
import java.io.*;
import java.net.*;
public class ClientComm {
public static final int DEFAULT_PORT = 6789;
private String host = "";
private int port = 0;
private OutputStream os = null;
66
67
}
while (true) {
line=sin.readLine();
if (DEBUG) {
System.out.println("Applet has read a line: " + line);
}
out.println(line);
if (line.equals("EndOfRecord")) break;
}
}
catch (IOException e) {
System.err.println(e);
}
// always be sure to close the socket
finally {
try {
if (s != null) s.close();
}
catch (IOException e2) { }
}
}
}
c. Create the Java program that implements the ClientCommExit class used in the applet:
ClientCommExit.java. This program deals with the special applet command of Server Exit.
import java.io.*;
import java.net.*;
public class ClientCommExit {
public static final int DEFAULT_PORT = 6789;
private String host = "";
private int port = 0;
private OutputStream os = null;
boolean DEBUG = true;
public ClientCommExit (String h, int p, OutputStream o) {
host = h;
port = ((p == 0) ? DEFAULT_PORT : p);
os = o;
Socket s = null;
PrintWriter out = new PrintWriter (os, true);
if (DEBUG) {
System.out.println("Applet about to create a socket on "
+ host + " at port " + port);
}
try {
// create a socket to communicate to the specified host and port
s = new Socket(host, port);
// create streams for reading and writing
BufferedReader sin = new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintStream sout = new PrintStream(s.getOutputStream(), true);
if (DEBUG) {
System.out.println("Applet has created sin and sout ");
}
// tell the user that we've connected
out.println("Connected to " + s.getInetAddress() +
":" + s.getPort());
68
if (DEBUG) {
System.out.println("Applet has connected to "+ s.getInetAddress() +
":" + s.getPort());
}
String line;
// read the first response (a line) from the server
line = sin.readLine();
if (DEBUG) {
System.out.println("Applet has read a line: " + line);
}
// write the line to the user
out.println(line);
out.flush();
// send the command choice to the server
sout.println("Server Exit");
if (DEBUG) {
System.out.println("Applet has sent sout the command: Server Exit");
}
}
catch (IOException e) {
System.err.println(e);
}
// always be sure to close the socket
finally {
try {
if (s != null) s.close();
}
catch (IOException e2) { }
}
}
}
d. Create the Java program that implements the ClientCommSQL class used in the applet:
ClientCommSQL.java. This program deals with the special applet commands for SQL statements.
import java.io.*;
import java.net.*;
public class ClientCommSQL {
public static final int DEFAULT_PORT = 6789;
private String host = "";
private int port = 0;
private OutputStream os = null;
boolean DEBUG = true;
public ClientCommSQL (String h, int p, int choice, String cmd, OutputStream
o) {
host = h;
port = ((p == 0) ? DEFAULT_PORT : p);
os = o;
Socket s = null;
PrintWriter out = new PrintWriter (os, true);
if (DEBUG) {
System.out.println("Applet about to create a socket on "
+ host + " at port " + port);
}
try {
// create a socket to communicate to the specified host and port
69
70
}
// always be sure to close the socket
finally {
try {
if (s != null) s.close();
}
catch (IOException e2) { }
}
}
}
71
java.net.*;
java.io.*;
java.sql.*;
class DispCus {
public static void DispCus(PrintStream out) {
String url = "jdbc:odbc:dbtest";
Connection con;
String query = "select * from Customer ";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "admin", "admin");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int rowCount = 1;
while (rs.next()) {
out.println("Row " + rowCount + ": ");
for (int i = 1; i <= numberOfColumns; i++) {
out.print("
Column " + i + ": ");
out.println(rs.getString(i));
}
out.println("");
rowCount++;
}
out.println("EndOfRecord");
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
}
import
import
import
public
java.net.*;
java.io.*;
java.sql.*;
class DispPro {
public static void DispPro(PrintStream out) {
String url = "jdbc:odbc:dbtest";
Connection con;
String query = "select * from Product ";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "admin", "admin");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int rowCount = 1;
while (rs.next()) {
out.println("Row " + rowCount + ": ");
for (int i = 1; i <= numberOfColumns; i++) {
out.print("
Column " + i + ": ");
out.println(rs.getString(i));
}
out.println("");
rowCount++;
}
out.println("EndOfRecord");
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
}
72
java.net.*;
java.io.*;
java.sql.*;
class DispTra {
public static void DispTra(PrintStream out) {
String url = "jdbc:odbc:dbtest";
Connection con;
String query = "select * from Transaction ";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
73
java.net.*;
java.io.*;
java.sql.*;
class ExeSQL {
public static void ExeSQL(PrintStream out, String sqlstr) {
String url = "jdbc:odbc:dbtest";
Connection con;
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "admin", "admin");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sqlstr);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int rowCount = 1;
while (rs.next()) {
out.println("Row " + rowCount + ": ");
for (int i = 1; i <= numberOfColumns; i++) {
out.print("
Column " + i + ": ");
out.println(rs.getString(i));
}
out.println("");
rowCount++;
}
out.println("EndOfRecord");
stmt.close();
74
con.close();
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
out.println("No result.");
out.println("EndOfRecord");
}
}
}