# QueryViewer.java An interactive database query viewer. Connects to the specified Oracle or Sybase database, executes a query, and presents the results in a JTable. Uses the following file:
* DBResultsTableModel.java Simple class that tells a JTable how to extract relevant data from a DBResults object (which is used to store the results from a database query).
############################################################################
package cwp;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
/** An interactive database query viewer. Connects to
* the specified Oracle or Sybase database, executes a query,
* and presents the results in a JTable.
*
*/
public class QueryViewer extends JFrame
implements ActionListener{
public static void main(String[] args) {
new QueryViewer();
}
private JTextField hostField, dbNameField,
queryField, usernameField;
private JRadioButton oracleButton, sybaseButton;
private JPasswordField passwordField;
private JButton showResultsButton;
Container contentPane;
private JPanel tablePanel;
public QueryViewer () {
super("Database Query Viewer");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
contentPane = getContentPane();
contentPane.add(makeControlPanel(), BorderLayout.NORTH);
pack();
setVisible(true);
}
/** When the "Show Results" button is pressed or
* RETURN is hit while the query textfield has the
* keyboard focus, a database lookup is performed,
* the results are placed in a JTable, and the window
* is resized to accommodate the table.
*/
public void actionPerformed(ActionEvent event) {
String host = hostField.getText();
String dbName = dbNameField.getText();
String username = usernameField.getText();
String password =
String.valueOf(passwordField.getPassword());
String query = queryField.getText();
int vendor;
if (oracleButton.isSelected()) {
vendor = DriverUtilities.ORACLE;
} else {
vendor = DriverUtilities.SYBASE;
}
if (tablePanel != null) {
contentPane.remove(tablePanel);
}
tablePanel = makeTablePanel(host, dbName, vendor,
username, password,
query);
contentPane.add(tablePanel, BorderLayout.CENTER);
pack();
}
// Executes a query and places the result in a
// JTable that is, in turn, inside a JPanel.
private JPanel makeTablePanel(String host,
String dbName,
int vendor,
String username,
String password,
String query) {
String driver = DriverUtilities.getDriver(vendor);
String url = DriverUtilities.makeURL(host, dbName, vendor);
DBResults results =
DatabaseUtilities.getQueryResults(driver, url,
username, password,
query, true);
JPanel panel = new JPanel(new BorderLayout());
if (results == null) {
panel.add(makeErrorLabel());
return(panel);
}
DBResultsTableModel model =
new DBResultsTableModel(results);
JTable table = new JTable(model);
table.setFont(new Font("Serif", Font.PLAIN, 17));
table.setRowHeight(28);
JTableHeader header = table.getTableHeader();
header.setFont(new Font("SansSerif", Font.BOLD, 13));
panel.add(table, BorderLayout.CENTER);
panel.add(header, BorderLayout.NORTH);
panel.setBorder
(BorderFactory.createTitledBorder("Query Results"));
return(panel);
}
// The panel that contains the textfields, checkboxes,
// and button.
private JPanel makeControlPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(makeHostPanel());
panel.add(makeUsernamePanel());
panel.add(makeQueryPanel());
panel.add(makeButtonPanel());
panel.setBorder
(BorderFactory.createTitledBorder("Query Data"));
return(panel);
}
// The panel that has the host and db name textfield and
// the driver radio buttons. Placed in control panel.
private JPanel makeHostPanel() {
JPanel panel = new JPanel();
panel.add(new JLabel("Host:"));
hostField = new JTextField(15);
panel.add(hostField);
panel.add(new JLabel(" DB Name:"));
dbNameField = new JTextField(15);
panel.add(dbNameField);
panel.add(new JLabel(" Driver:"));
ButtonGroup vendorGroup = new ButtonGroup();
oracleButton = new JRadioButton("Oracle", true);
vendorGroup.add(oracleButton);
panel.add(oracleButton);
sybaseButton = new JRadioButton("Sybase");
vendorGroup.add(sybaseButton);
panel.add(sybaseButton);
return(panel);
}
// The panel that has the username and password textfields.
// Placed in control panel.
private JPanel makeUsernamePanel() {
JPanel panel = new JPanel();
usernameField = new JTextField(10);
passwordField = new JPasswordField(10);
panel.add(new JLabel("Username: "));
panel.add(usernameField);
panel.add(new JLabel(" Password:"));
panel.add(passwordField);
return(panel);
}
// The panel that has textfield for entering queries.
// Placed in control panel.
private JPanel makeQueryPanel() {
JPanel panel = new JPanel();
queryField = new JTextField(40);
queryField.addActionListener(this);
panel.add(new JLabel("Query:"));
panel.add(queryField);
return(panel);
}
// The panel that has the "Show Results" button.
// Placed in control panel.
private JPanel makeButtonPanel() {
JPanel panel = new JPanel();
showResultsButton = new JButton("Show Results");
showResultsButton.addActionListener(this);
panel.add(showResultsButton);
return(panel);
}
// Shows warning when bad query sent.
private JLabel makeErrorLabel() {
JLabel label = new JLabel("No Results", JLabel.CENTER);
label.setFont(new Font("Serif", Font.BOLD, 36));
return(label);
}
}
Aug 06
extract relevant data from a DBResults
Aug 05
EmployeeTest2.java: A test case for the database utilities. Prints results formatted as an HTML table.
package cwp;
import java.sql.*;
/** Connect to Oracle or Sybase and print "employees" table
* as an HTML table.
*
*/
public class EmployeeTest2 {
public static void main(String[] args) {
if (args.length < 5) {
printUsage();
return;
}
String vendorName = args[4];
int vendor = DriverUtilities.getVendor(vendorName);
if (vendor == DriverUtilities.UNKNOWN) {
printUsage();
return;
}
String driver = DriverUtilities.getDriver(vendor);
String host = args[0];
String dbName = args[1];
String url =
DriverUtilities.makeURL(host, dbName, vendor);
String username = args[2];
String password = args[3];
String query = "SELECT * FROM employees";
DBResults results =
DatabaseUtilities.getQueryResults(driver, url,
username, password,
query, true);
System.out.println(results.toHTMLTable("CYAN"));
}
private static void printUsage() {
System.out.println("Usage: EmployeeTest2 host dbName " +
"username password oracle|sybase.");
}
}
Aug 05
DBResults.java: Class to store completed results of a JDBC Query. Differs from a ResultSet in several ways
# DBResults.java Class to store completed results of a JDBC Query. Differs from a ResultSet in several ways: * ResultSet doesn?t necessarily have all the data; reconnection to database occurs as you ask for later rows. * This class stores results as strings, in arrays. * This class includes DatabaseMetaData (database product name and version) and ResultSetMetaData (the column names). * This class has a toHTMLTable method that turns the results into a long string corresponding to an HTML table.
package cwp;
import java.sql.*;
import java.util.*;
/** Class to store completed results of a JDBC Query.
* Differs from a ResultSet in several ways:
*
*
ResultSet doesn't necessarily have all the data;
* reconnection to database occurs as you ask for
* later rows.
*
This class stores results as strings, in arrays.
*
This class includes DatabaseMetaData (database product
* name and version) and ResultSetMetaData
* (the column names).
*
This class has a toHTMLTable method that turns
* the results into a long string corresponding to
* an HTML table.
*
*
*/
public class DBResults {
private Connection connection;
private String productName;
private String productVersion;
private int columnCount;
private String[] columnNames;
private Vector queryResults;
String[] rowData;
public DBResults(Connection connection,
String productName,
String productVersion,
int columnCount,
String[] columnNames) {
this.connection = connection;
this.productName = productName;
this.productVersion = productVersion;
this.columnCount = columnCount;
this.columnNames = columnNames;
rowData = new String[columnCount];
queryResults = new Vector();
}
public Connection getConnection() {
return(connection);
}
public String getProductName() {
return(productName);
}
public String getProductVersion() {
return(productVersion);
}
public int getColumnCount() {
return(columnCount);
}
public String[] getColumnNames() {
return(columnNames);
}
public int getRowCount() {
return(queryResults.size());
}
public String[] getRow(int index) {
return((String[])queryResults.elementAt(index));
}
public void addRow(String[] row) {
queryResults.addElement(row);
}
/** Output the results as an HTML table, with
* the column names as headings and the rest of
* the results filling regular data cells.
*/
public String toHTMLTable(String headingColor) {
StringBuffer buffer =
new StringBuffer("\n");
if (headingColor != null) {
buffer.append(" \n ");
} else {
buffer.append(" \n ");
}
for(int col=0; col" + columnNames[col]);
}
for(int row=0; row\n ");
String[] rowData = getRow(row);
for(int col=0; col" + rowData[col]);
}
}
buffer.append("\n");
return(buffer.toString());
}
}
Aug 04
DatabaseUtilities.java: Several general-purpose utilities discussed and used in the chapter.
package cwp;
import java.sql.*;
/** Three database utilities:
* 1) getQueryResults. Connects to a database, executes
* a query, retrieves all the rows as arrays
* of strings, and puts them inside a DBResults
* object. Also places the database product name,
* database version, and the names of all the columns
* into the DBResults object. This has two versions:
* one that makes a new connection and another that
* uses an existing connection.
* 2) createTable. Given a table name, a string denoting
* the column formats, and an array of strings denoting
* the row values, this method connects to a database,
* removes any existing versions of the designated
* table, issues a CREATE TABLE command with the
* designated format, then sends a series of INSERT INTO
* commands for each of the rows. Again, there are
* two versions: one that makes a new connection and
* another that uses an existing connection.
* 3) printTable. Given a table name, this connects to
* the specified database, retrieves all the rows,
* and prints them on the standard output.
*/
public class DatabaseUtilities {
/** Connect to database, execute specified query,
* and accumulate results into DBRresults object.
* If the database connection is left open (use the
* close argument to specify), you can retrieve the
* connection via DBResults.getConnection.
*/
public static DBResults getQueryResults(String driver,
String url,
String username,
String password,
String query,
boolean close) {
try {
Class.forName(driver);
Connection connection =
DriverManager.getConnection(url, username, password);
return(getQueryResults(connection, query, close));
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
return(null);
} catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
return(null);
}
}
/** Retrieves results as in previous method, but uses
* an existing connection instead of opening a new one.
*/
public static DBResults getQueryResults(Connection connection,
String query,
boolean close) {
try {
DatabaseMetaData dbMetaData = connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
String productVersion =
dbMetaData.getDatabaseProductVersion();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData resultsMetaData =
resultSet.getMetaData();
int columnCount = resultsMetaData.getColumnCount();
String[] columnNames = new String[columnCount];
// Column index starts at 1 (ala SQL) not 0 (ala Java).
for(int i=1; i
Aug 04
EmployeeTest.java: A test case for the database utilities. Prints results in plain text.
package cwp;
import java.sql.*;
/** Connect to Oracle or Sybase and print "employees" table.
*
*/
public class EmployeeTest {
public static void main(String[] args) {
if (args.length < 5) {
printUsage();
return;
}
String vendorName = args[4];
int vendor = DriverUtilities.getVendor(vendorName);
if (vendor == DriverUtilities.UNKNOWN) {
printUsage();
return;
}
String driver = DriverUtilities.getDriver(vendor);
String host = args[0];
String dbName = args[1];
String url =
DriverUtilities.makeURL(host, dbName, vendor);
String username = args[2];
String password = args[3];
DatabaseUtilities.printTable(driver, url,
username, password,
"employees", 12, true);
}
private static void printUsage() {
System.out.println("Usage: EmployeeTest host dbName " +
"username password oracle|sybase.");
}
}
Aug 03
Example Java Programs
HelloWorld.java
public class HelloWorld {
// method main(): ALWAYS the APPLICATION entry point
public static void main (String[] args) {
System.out.println ("Hello World!");
}
}
// Print Today's Date
import java.util.*;
public class HelloDate {
public static void main (String[] args) {
System.out.println ("Hello, it's: ");
System.out.println(new Date());
}
}
//example: function call in Java
public class FunctionCall {
public static void funct1 () {
System.out.println ("Inside funct1");
}
public static void main (String[] args) {
int val;
System.out.println ("Inside main");
funct1();
System.out.println ("About to call funct2");
val = funct2(8);
System.out.println ("funct2 returned a value of " + val);
System.out.println ("About to call funct2 again");
val = funct2(-3);
System.out.println ("funct2 returned a value of " + val);
}
public static int funct2 (int param) {
System.out.println ("Inside funct2 with param " + param);
return param * 2;
}
}
//Array in Java
public class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // DECLARE an array of integers
anArray = new int[10]; // CREATE an array of integers
// assign a value to each array element
for (int i = 0; i < anArray.length; i++) {
anArray[i] = i;
}
// print a value from each array element
for (int i = 0; i < anArray.length; i++) {
System.out.print(anArray[i] + " ");
}
System.out.println();
}
}
//class usage in Java
class Point2d {
/* The X and Y coordinates of the point--instance variables */
private double x;
private double y;
private boolean debug; // A trick to help with debugging
public Point2d (double px, double py) { // Constructor
x = px;
y = py;
debug = false; // turn off debugging
}
public Point2d () { // Default constructor
this (0.0, 0.0); // Invokes 2 parameter Point2D constructor
}
// Note that a this() invocation must be the BEGINNING of
// statement body of constructor
public Point2d (Point2d pt) { // Another consructor
x = pt.getX();
y = pt.getY();
// a better method would be to replace the above code with
// this (pt.getX(), pt.getY());
// especially since the above code does not initialize the
// variable debug. This way we are reusing code that is already
// working.
}
public void dprint (String s) {
// print the debugging string only if the "debug"
// data member is true
if (debug)
System.out.println("Debug: " + s);
}
public void setDebug (boolean b) {
debug = b;
}
public void setX(double px) {
dprint ("setX(): Changing value of X from " + x + " to " + px );
x = px;
}
public double getX() {
return x;
}
public void setY(double py) {
dprint ("setY(): Changing value of Y from " + y + " to " + py );
y = py;
}
public double getY() {
return y;
}
public void setXY(double px, double py) {
setX(px);
setY(py);
}
public double distanceFrom (Point2d pt) {
double dx = Math.abs(x - pt.getX());
double dy = Math.abs(y - pt.getY());
// check out the use of dprint()
dprint ("distanceFrom(): deltaX = " + dx);
dprint ("distanceFrom(): deltaY = " + dy);
return Math.sqrt((dx * dx) + (dy * dy));
}
public double distanceFromOrigin () {
return distanceFrom (new Point2d ( ));
}
public String toStringForXY() {
String str = "(" + x + ", " + y;
return str;
}
public String toString() {
String str = toStringForXY() + ")";
return str;
}
}
//read integer from Keyboard
import java.io.*;
import java.util.*;
public class KeyboardIntegerReader {
public static void main (String[] args) throws java.io.IOException {
String s1;
String s2;
int num = 0;
// set up the buffered reader to read from the keyboard
BufferedReader br = new BufferedReader (new InputStreamReader (
System.in));
boolean cont = true;
while (cont)
{
System.out.print ("Enter an integer:");
s1 = br.readLine();
StringTokenizer st = new StringTokenizer (s1);
s2 = "";
while (cont && st.hasMoreTokens())
{
try
{
s2 = st.nextToken();
num = Integer.parseInt(s2);
cont = false;
}
catch (NumberFormatException n)
{
System.out.println("The value in \"" + s2 + "\" is not an
integer");
}
}
}
System.out.println ("You entered the integer: " + num);
}
}
//read data from keyboard
import java.io.*;
import java.util.*;
public class KeyboardReader
{
public static void main (String[] args) throws java.io.IOException
{
String s1;
String s2;
double num1, num2, product;
// set up the buffered reader to read from the keyboard
BufferedReader br = new BufferedReader (new InputStreamReader (
System.in));
System.out.println ("Enter a line of input");
s1 = br.readLine();
System.out.println ("The line has " + s1.length() + " characters");
System.out.println ();
System.out.println ("Breaking the line into tokens we get:");
int numTokens = 0;
StringTokenizer st = new StringTokenizer (s1);
while (st.hasMoreTokens())
{
s2 = st.nextToken();
numTokens++;
System.out.println (" Token " + numTokens + " is: " + s2);
}
}
}
//read from file
import java.io.*;
import java.util.*;
public class MyFileReader
{
public static void main (String[] args) throws java.io.IOException
{
String s1;
String s2;
// set up the buffered reader to read from the keyboard
BufferedReader br = new BufferedReader (new FileReader
("MyFileReader.txt"));
s1 = br.readLine();
System.out.println ("The line is " + s1);
System.out.println ("The line has " + s1.length() + " characters");
System.out.println ();
System.out.println ("Breaking the line into tokens we get:");
int numTokens = 0;
StringTokenizer st = new StringTokenizer (s1);
while (st.hasMoreTokens())
{
s2 = st.nextToken();
numTokens++;
System.out.println (" Token " + numTokens + " is: " + s2);
}
}
}
//exception handling in Java
public class HelloWorldException {
public static void main (String[] args) throws Exception {
System.out.println("Bienvenitos!");
throw new Exception("Generic Exception");
}
}
//exception handling
import java.io.*;
import java.util.*;
/** Causes a compilation error due to an unhandled Exception
*/
public class KeyboardReaderError {
public static void main (String[] args) { // throws java.io.IOException
String s1;
String s2;
double num1, num2, product;
// set up the buffered reader to read from the keyboard
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
System.out.println ("Enter a line of input");
/* Following line triggers the error. Error will show the type of
unhandled exception and where the call occurs */
s1 = br.readLine();
System.out.println ("The line has " + s1.length() + " characters");
System.out.println ();
System.out.println ("Breaking the line into tokens we get:");
int numTokens = 0;
StringTokenizer st = new StringTokenizer (s1);
while (st.hasMoreTokens()) {
s2 = st.nextToken();
numTokens++;
System.out.println (" Token " + numTokens + " is: " + s2);
}
}
}
//encounters an error
import java.io.*;
// This program shows a stack track that occurs when java
// encounters a terminal error when running a program.
public class DivBy0
{
public static void funct1 ()
{
System.out.println ("Inside funct1()");
funct2();
}
public static void main (String[] args)
{
int val;
System.out.println ("Inside main()");
funct1();
}
public static void funct2 ()
{
System.out.println ("Inside funct2()");
int i, j, k;
i = 10;
j = 0;
k = i/j;
}
}
Aug 03
FruitCreation.java: Creates a simple table named fruits in either an Oracle or a Sybase database.
FruitCreation.java Creates a simple table named fruits in either an Oracle or a Sybase database.
package cwp;
import java.sql.*;
/** Creates a simple table named "fruits" in either
* an Oracle or a Sybase database.
*
*/
public class FruitCreation {
public static void main(String[] args) {
if (args.length < 5) {
printUsage();
return;
}
String vendorName = args[4];
int vendor = DriverUtilities.getVendor(vendorName);
if (vendor == DriverUtilities.UNKNOWN) {
printUsage();
return;
}
String driver = DriverUtilities.getDriver(vendor);
String host = args[0];
String dbName = args[1];
String url =
DriverUtilities.makeURL(host, dbName, vendor);
String username = args[2];
String password = args[3];
String format =
"(quarter int, " +
"apples int, applesales float, " +
"oranges int, orangesales float, " +
"topseller varchar(16))";
String[] rows =
{ "(1, 32248, 3547.28, 18459, 3138.03, 'Maria')",
"(2, 35009, 3850.99, 18722, 3182.74, 'Bob')",
"(3, 39393, 4333.23, 18999, 3229.83, 'Joe')",
"(4, 42001, 4620.11, 19333, 3286.61, 'Maria')" };
Connection connection =
DatabaseUtilities.createTable(driver, url,
username, password,
"fruits", format, rows,
false);
// Test to verify table was created properly. Reuse
// old connection for efficiency.
DatabaseUtilities.printTable(connection, "fruits",
11, true);
}
private static void printUsage() {
System.out.println("Usage: FruitCreation host dbName " +
"username password oracle|sybase.");
}
}
Aug 02
Example illustrating inheritance and abstract classes
illustrating inheritance এবং abstract classes এর উদাহরণ
- Shape.java সব, বদ্ধ খোলা, বাঁকা, এবং সোজা পার্শ্বে ধারবিশিষ্ট আকার এর জন্য প্যারেন্ট ক্লাস (সারাংশ)।
- Curve.java একটি (সারাংশ) বাঁকা আকার (খোলা বা বন্ধ)।
- StraightEdgedShape.java সরাসরি ধার সম্বলিত একটি আকৃতি (খোলা বা বন্ধ)।
- Measurable.java পরিমাপযোগ্য এলাকায় ইন্টারফেস ডিফাইনিং ক্লাস।
- Circle.java একটি বৃত্ত যা আকার প্রসারিত করে এবং পরিমাপ প্রয়োগ করে।
- MeasureUtil.java পরিমাপযোগ্য স্থানের উপর কাজ করে।
- Polygon.java সরাসরি ধার সম্বলিত একটি বদ্ধ আকৃতি; StraightEdgedShape প্রসারিত করে এবং পরিমাপ প্রয়োগ করে।
- Rectangle.java একটি আয়তক্ষেত্র যা পরিমাপযোগ্য ইন্টারফেস ধারণ করে; বহুভুজে প্রসারিত করে।
- MeasureTest.java উদাহরণ এর জন্য ড্রাইভার।
Shape.java
/** The parent class for all closed, open, curved, and
* straight-edged shapes.
*
public abstract class Shape {
protected int x, y;
public int getX() {
return(x);
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return(y);
}
public void setY(int y) {
this.y = y;
}
}
Curve.java
একটি (সারাংশ) বাঁকা আকার (খোলা বা বন্ধ) । Curve.java An (abstract) curved Shape (open or closed)
/** A curved shape (open or closed). Subclasses will include * arcs and circles. *
public abstract class Curve extends Shape {}
StraightEdgedShape.java
সরাসরি ধার সম্বলিত একটি আকৃতি (খোলা বা বন্ধ) । A Shape with straight edges (open or closed).
/** A Shape with straight edges (open or closed). Subclasses
* will include Line, LineSegment, LinkedLineSegments,
* and Polygon.
*
public abstract class StraightEdgedShape extends Shape {}
Measurable.java
পরিমাপযোগ্য এলাকায় ইন্টারফেস ডিফাইনিং ক্লাস। Interface defining classes with measurable areas
/** Used in classes with measurable areas.
*
**************
public interface Measurable {
double getArea();
}
Circle.java
একটি বৃত্ত যা আকার প্রসারিত করে এবং পরিমাপ প্রয়োগ করে । A circle that extends Shape and implements Measurable.
/** A circle. Since you can calculate the area of
* circles, class implements the Measurable interface.
*
public class Circle extends Curve implements Measurable {
private double radius;
public Circle(int x, int y, double radius) {
setX(x);
setY(y);
setRadius(radius);
}
public double getRadius() {
return(radius);
}
public void setRadius(double radius) {
this.radius = radius;
}
/** Required for Measurable interface. */
public double getArea() {
return(Math.PI * radius * radius);
}
}
MeasureUtil.java
পরিমাপযোগ্য স্থানের উপর কাজ করে । Operates on Measurable instances
/** Some operations on Measurable instances.
*
public class MeasureUtil {
public static double maxArea(Measurable m1,
Measurable m2) {
return(Math.max(m1.getArea(), m2.getArea()));
}
public static double totalArea(Measurable[] mArray) {
double total = 0;
for(int i=0; i
