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());
  } 
}

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                                

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.");
  }
}

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;
 }

}


জাভাস্ক্রিপ্ট কুইজ । JavaScript Quiz

[slickquiz id=14]

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.");
  }
}



						
						
						
		

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

 

Some simple utilities for building Oracle and Sybase JDBC connections

এই সাধারণ উদ্দেশ্যে তৈরিকৃত কোড নয় – এটা আমাদের লোকাল সেটআপ এর ক্ষেত্রে প্রযোজ্য।


 

 

package cwp;

/** Some simple utilities for building Oracle and Sybase
 *  JDBC connections. This is not general-purpose
 *  code -- it is specific to my local setup.
 */

public class DriverUtilities {
  public static final int ORACLE = 1;
  public static final int SYBASE = 2;
  public static final int UNKNOWN = -1;

  /** Build a URL in the format needed by the
   *  Oracle and Sybase drivers I am using.
   */
  
  public static String makeURL(String host, String dbName,
                               int vendor) {
    if (vendor == ORACLE) {
      return("jdbc:oracle:thin:@" + host + ":1521:" + dbName);
    } else if (vendor == SYBASE) {
      return("jdbc:sybase:Tds:" + host  + ":1521" +
             "?SERVICENAME=" + dbName);
    } else {
      return(null);
    }
  }

  /** Get the fully qualified name of a driver. */
  
  public static String getDriver(int vendor) {
    if (vendor == ORACLE) {
      return("oracle.jdbc.driver.OracleDriver");
    } else if (vendor == SYBASE) {
      return("com.sybase.jdbc.SybDriver");
    } else {
      return(null);
    }
  }

  /** Map name to int value. */

  public static int getVendor(String vendorName) {
    if (vendorName.equalsIgnoreCase("oracle")) {
      return(ORACLE);
    } else if (vendorName.equalsIgnoreCase("sybase")) {
      return(SYBASE);
    } else {
      return(UNKNOWN);
    }
  }
}

FruitTest.java: A class that connects to either an Oracle or a Sybase database and prints out the values of predetermined columns in the “fruits” table.

# FruitTest.java  A class that connects to either an Oracle or a Sybase database and prints 
  out the values of predetermined columns in the "fruits" table. 

package cwp;

import java.sql.*;

/** A JDBC example that connects to either an Oracle or
 *  a Sybase database and prints out the values of
 *  predetermined columns in the "fruits" table.
 *  


 */

public class FruitTest {

  /** Reads the hostname, database name, username, password,
   *  and vendor identifier from the command line. It
   *  uses the vendor identifier to determine which
   *  driver to load and how to format the URL. The
   *  driver, URL, username, host, and password are then
   *  passed to the showFruitTable method.
   */
  
  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];
    showFruitTable(driver, url, username, password);
  }

  /** Get the table and print all the values. */
  
  public static void showFruitTable(String driver,
                                    String url,
                                    String username,
                                    String password) {
    try {
      // Load database driver if not already loaded
      Class.forName(driver);
      // Establish network connection to database
      Connection connection =
        DriverManager.getConnection(url, username, password);
      // Look up info about the database as a whole.
      DatabaseMetaData dbMetaData = connection.getMetaData();
      String productName =
        dbMetaData.getDatabaseProductName();
      System.out.println("Database: " + productName);
      String productVersion =
        dbMetaData.getDatabaseProductVersion();
      System.out.println("Version: " + productVersion + "\n");
      System.out.println("Comparing Apples and Oranges\n" +
                         "============================");
      Statement statement = connection.createStatement();
      String query = "SELECT * FROM fruits";
      // Send query to database and store results
      ResultSet resultSet = statement.executeQuery(query);
      // Look up information about a particular table
      ResultSetMetaData resultsMetaData =
        resultSet.getMetaData();
      int columnCount = resultsMetaData.getColumnCount();
      // Column index starts at 1 (ala SQL) not 0 (ala Java).
      for(int i=1; i

সিএসএস কুইজ । CSS Quiz

[slickquiz id=13]