Test

Powered by Blogger.

Wednesday 11 July 2012

JDBC

Introduction to JDB


Java started as an elegant and promising Web programming language. Thereafter, its transition to hard-core computing environment
 is a phenomenal feat. Apart from its significance on client-side programming, Java has been outstanding in developing mission-critical
 enterprise-scale applications and hence its immense contribution to server-side computing gets all round attention. Thus Java as
 a programming language for enterprise computing has been doing well for the past couple of years. As every enterprise includes a
 database, Sun Microsystems has to come with necessary features for making Java to shine in database programming as well.
 In this overview, we discuss about the role of Java Database Connectivity in accomplishing database programming with ease.



Database Programming with Java
Database Programming with Java

Java provides database programmers some distinct advantages, such as easy object to relational mapping, database independence
 and distributed computing. For languages, such as C++ and Smalltalk, there is a need for tools for mapping their objects to
 relational entities. Java provides an alternative to these tools that frees us from the proprietary interfaces associated with
 database programming. With the "write once, compile once, run anywhere" power that JDBC offers us, Java's database connectivity
 allows us to concentrate on the translation of relational data into objects instead of how we can get that data from the database.

A Java database application does not care what its database engine is. No matter how many times the database engine changes,
 the application itself need never change. In addition, a company can build a class library that maps its business objects to
 database entities in such a way that applications do not even know whether or not their objects are being stored in a database.

Java affects the way we distribute and maintain application. Currently a Web application allows user to download a bunch of flight
 information as an HTML page. While viewing the page for a particular flight, suppose some one makes a reservation for a seat on that
 flight and this process will not be available to the viewers as the page is just a copy of data from the database. To view the change
 that just occurred, the viewers again have to contact the database to get the latest data. If we reconstruct the same Web application
 using Java RMI to retrieve the data from a single flight object on the server, any number of users can view the data simultaneously and
 if there is any reservation or any change taking place, immediately the changes made to the data will be sent back to all the users and
 hence the users can avail the latest data at any time. Thus JDBC can combine with Java RMI to develop distributed enterprise-scale
 mission-critical three-tier database applications.
JDBC for Relational Databases

There are three main database technologies. They are relational, object and object-relational. A Java application can access any one
 of these database architectures. The overwhelming majority of today's database applications use relational databases. The JDBC API is
 thus heavily biased toward relational databases and their standard query language, SQL. Relational databases find and provide
 relationships between data and Java, as a object solution makes common cause with relational database technology due to the
 fact that object-oriented philosophy dictates that an object's behavior is inseparable from its data. In choosing the
 object-oriented reality of Java, we need to create a translation layer that maps the relational world into our object
 world. Thus with the goal of accessing relational databases, JDBC API specification has been defined by Sun Microsystems
 with the help of popular database vendors.

 What is JDBC?

JDBC is essentially an Application Programming Interface (API) for executing SQL statements, and extracting the results.
Using this API, we can write database clients, such as Java applets, servlets and Enterprise JavaBeans, that connect to a
relational database, such as Oracle, MySQL, Sybase, Informix, Ingres, PostgreSQL, or any other database that implements this API,
 execute SQL statements, and process the results extracted from the database.
JDBC Versions

JDBC 2.0 API is the latest version of JDBC API available in the java.sql package. The previous version focused primarily on basic
 database programming services such as creating connections, executing statements and prepared statements, running batch queries, etc.
 However, the current API supports batch updates, scrollable resultsets, transaction isolation, and the new SQL:1999 data types such as
 BLOB and CLOB in addition to the SQL2 data types.

JDBC 2.0 Optional Package API is available in the javax.sql package and is distributed with the enterprise edition of Java 2, that is J2EE.
 The optional package addresses Java Naming and Directory Interface (JNDI)-based data sources for managing connections, connection pooling,
 distributed transactions, and rowsets.
The Benefits of JDBC

The JDBC API provides a set of implementation-independent generic database access methods for the above mentioned SQL-compliant databases.
 JDBC abstracts much of the vendor-specific details and generalizes the most common database access functions. Thus resulted a set of classes
 and interfaces of the java.sql package that can be used with any database providing JDBC connectivity through a vendor-specific JDBC driver
 in a consistent way. Thus if our application conforms to the most commonly available database features, we should be able to reuse
 an application with another database simply by switching to a new JDBC driver. In other words, JDBC enables us to write applications
 that access relational databases without any thought as to which particular database we are using.

Also database connectivity is not just connecting to databases and executing statements. In an enterprise-level application environment
, there are some important requirements to be met, such as optimizing network resources by employing connection pooling, and implementing
distributed transactions. JDBC has all these features in accomplishing advanced database programming.
The JDBC Drivers

A database vendor typically provides a set of APIs for accessing the data managed by the database server. Popular database vendors have
 supplied some proprietary APIs for client access. Client applications written in native languages such as C and C++ can make these API
 calls for database access directly. The JDBC API provides a Java-language alternative to these vendor-specific APIs. Though this takes
 away the need to access vendor-specific native APIs for database access, the implementation of the JDBC layer still need to make these
 native calls for data access.

JDBC accomplishes its goals through a set of Java interfaces, each gets implemented differently by different vendors. The set of classes
 that implement the JDBC interfaces for a particular database engine is called a JDBC driver. Hence the necessity of a JDBC driver for
 each database server. In building a database application, we do not have to think about the implementation of these underlying classes
 at all as the whole point of using JDBC is to hide the specifics of each database and let us concentrate on our application.
 A JDBC driver is a middleware layer that translates the JDBC calls to the vendor-specific APIs. The Java VM uses the JDBC
 driver to translate the generalized JDBC calls into vendor-specific database calls that the database understands.

There are a number of approaches for connecting from our application to a database server via a database driver.

JDBC-ODBC Bridge - Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows
environment. ODBC is a Windows API standard for SQL and it is based on X/Open Call-Level Interface (CLI) specification, which is
a standard API for database access. CLI is intended to be vendor, platform, and database neutral. But ODBC API defines a set of
 functions for directly accessing the data without the need for embedding SQL statements in client applications coded in higher
 level languages.

The JDBC API is originally based on the ODBC API. Thus, it becomes feasible for the first category of JDBC drivers providing
a bridge between the JDBC API and the ODBC API. This bridge translates the standard JDBC calls to corresponding ODBC calls. The
 driver then delegates these calls to the data source. Here, the Java classes for the JDBC API and the JDBC-ODBC bridge are invoked
 within the client application process. Similarly, the ODBC layer executes in another process. This configuration requires the client
 application to have the JDBC-ODBC bridge API, the ODBC driver, and the native language level API, such as the OCI library for Oracle
 installed on each client machine.

Each data access call has to go through many layers, this approach for data access is inefficient for high-performance database
access requirements. Though this is not a preferred one, this has to be used in some situations for example, a Microsoft Access
2000 database can be only be accessed using the JDBC-ODBC bridge.

Part Java, Part Native Driver - This approach use a mixture of Java implementation and vendor-specific native APIs for data access.
 This one is a little bit faster than the earlier one. When a database call is made using JDBC, the driver translates the request
 into vendor-specific API calls. The database will process the request and send the results back through the API, which will forward
 them back to the JDBC driver. The JDBC driver will format the results to confirm to the JDBC standard and return them to the program.
 In this approach, the native JDBC driver, which is part Java and part native code, should be installed on each client along with the
 vendor-specific native language API. The native code uses vendor-specific protocols for communicating with the database. The improved
 efficiency makes this a preferred method over the use of the earlier one.

Intermediate Database Access Server This approach is based on intermediate (middleware) database servers with the ability to connect
multiple Java clients to multiple database servers. In this configuration, clients connect to various database servers via an intermediate
 server that acts as a gateway for multiple database servers. While the specific protocol used between clients and the intermediate server
 depends on the middleware server vendor, the intermediate server can use different native protocols to connect to different databases.
 The Java client application sends a JDBC call through a JDBC driver to the intermediate data access server. The middle-tier then handles
 the request using another driver, for example the above one, to complete the request. This is good because the intermediate server can
 abstract details of connections to database servers.

Pure Java Drivers - This a pure Java alternative to part Java, part native driver. These drivers convert the JDBC API calls to direct
network calls using vendor-specific networking by making direct socket connections with the database like Oracle Thin JDBC Driver.
 This is the most efficient method of accessing databases both in performance and development time. It also the simplest to deploy
 since there are no additional libraries or middleware to install. All major database vendors, such as Oracle, Sybase, and Microsoft,
 provide this type of drivers for their databases.
Alternatives to JDBC

There are two major alternatives to JDBC at present. They are ODBC and SQLJ, a non-approved Java standard for database access.

Without JDBC, only disparate, proprietary database access solutions exist. These solutions force the developer to build a layer
 of abstraction on top of them in order to create database-independent code. The ODBC solution provide this universal abstraction
 layer for languages, such as C and C++, and popular developmental tools, such as Delphi, PowerBuilder, and VisualBasic. But ODBC
 can not enjoy the platform independence of Java as ODBC is restricted to Windows platform. On using JDBC, the server application
 can pick the database at run time based on which client is connecting. Thus JDBC facilitates to change the database just by
 changing the JDBC URL and driver name without adding any new code.

connect to database using java



Connecting to a MySQL Database in Java


    

In java we have been provided with some classes and APIs with which we can make use of the database as we like.
Database plays as very important role in the programming because we have to store the values somewhere in the back- end.
So, we should know how we can manipulate the data in the database with the help of java,  instead of going to database for
a manipulation. We have many database provided like Oracle, MySQL etc. We are using MySQL for developing this application.

In this section, you will learn how to connect the MySQL database with the Java file. Firstly, we need to establish a
connection between MySQL and Java files with the help of MySQL driver .  Now we will make our  account in MySQL database
so that we can get connected to the database. After establishing a connection  we can access or retrieve data form MySQL
database. We are going to make a program on connecting to a MySQL database, after going through this program you will be
 able to establish a connection on your own PC.

Description of program:

This program establishes the connection between MySQL database and java files with the help of various types of APIs interfaces
and methods. If connection is established then it shows "Connected to the database" otherwise it will displays a message "Disconnected
from database".

Description of code:

Connection:
This is an interface in  java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and
java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver):
This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that
 matches class with given string.

DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like:

    url: - Database url where stored or created your database
  userName: - User name of MySQL
  password: -Password of MySQL

con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the database.

printStackTrace():
The method is used to show error messages. If the connection is not established then exception is thrown and print the message.

import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
  System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "jdbctutorial";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root";
  String password = "root";
  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
}

java calculator

 JAVA CALCULATOR

/**
  This is a simple calculator program can any one take and use.

   */
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200></applet>
public class Calculator extends JApplet {
   public void init() {
      CalculatorPanel calc=new CalculatorPanel();
      getContentPane().add(calc);
      }
   }

   class CalculatorPanel extends JPanel implements ActionListener {
      JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
      static JTextField result=new JTextField("0",45);
      static String lastCommand=null;
      JOptionPane p=new JOptionPane();
      double preRes=0,secVal=0,res;

      private static void assign(String no)
        {
         if((result.getText()).equals("0"))
            result.setText(no);
          else if(lastCommand=="=")
           {
            result.setText(no);
            lastCommand=null;
           }
          else
            result.setText(result.getText()+no);
         }

      public CalculatorPanel() {
         setLayout(new BorderLayout());
         result.setEditable(false);
         result.setSize(300,200);
         add(result,BorderLayout.NORTH);
         JPanel panel=new JPanel();
         panel.setLayout(new GridLayout(4,4));

         n7=new JButton("7");
         panel.add(n7);
         n7.addActionListener(this);
         n8=new JButton("8");
         panel.add(n8);
         n8.addActionListener(this);
         n9=new JButton("9");
         panel.add(n9);
         n9.addActionListener(this);
         div=new JButton("/");
         panel.add(div);
         div.addActionListener(this);

         n4=new JButton("4");
         panel.add(n4);
         n4.addActionListener(this);
         n5=new JButton("5");
         panel.add(n5);
         n5.addActionListener(this);
         n6=new JButton("6");
         panel.add(n6);
         n6.addActionListener(this);
         mul=new JButton("*");
         panel.add(mul);
         mul.addActionListener(this);

         n1=new JButton("1");
         panel.add(n1);
         n1.addActionListener(this);
         n2=new JButton("2");
         panel.add(n2);
         n2.addActionListener(this);
         n3=new JButton("3");
         panel.add(n3);
         n3.addActionListener(this);
         minus=new JButton("-");
         panel.add(minus);
         minus.addActionListener(this);

         dot=new JButton(".");
         panel.add(dot);
         dot.addActionListener(this);
         n0=new JButton("0");
         panel.add(n0);
         n0.addActionListener(this);
         
         equal=new JButton("=");
         panel.add(equal);
         equal.addActionListener(this);
         plus=new JButton("+");
         panel.add(plus);
         plus.addActionListener(this);
         add(panel,BorderLayout.CENTER);
      }
      public void actionPerformed(ActionEvent ae)
         {
      if(ae.getSource()==n1) assign("1");
      else if(ae.getSource()==n2) assign("2");
      else if(ae.getSource()==n3) assign("3");
      else if(ae.getSource()==n4) assign("4");
      else if(ae.getSource()==n5) assign("5");
      else if(ae.getSource()==n6) assign("6");
      else if(ae.getSource()==n7) assign("7");
      else if(ae.getSource()==n8) assign("8");
      else if(ae.getSource()==n9) assign("9");
      else if(ae.getSource()==n0) assign("0");
     
      else if(ae.getSource()==dot)
            {
             if(((result.getText()).indexOf("."))==-1)
                result.setText(result.getText()+".");
           }
      else if(ae.getSource()==minus)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="-";
             result.setText("0");
             }
      else if(ae.getSource()==div)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="/";
             result.setText("0");
             }
      else if(ae.getSource()==equal)
             {
             secVal=Double.parseDouble(result.getText());
             if(lastCommand.equals("/"))
                  res=preRes/secVal;
             else if(lastCommand.equals("*"))
                  res=preRes*secVal;
             else if(lastCommand.equals("-"))
                  res=preRes-secVal;
             else if(lastCommand.equals("+"))
                  res=preRes+secVal;
             result.setText(" "+res);
             lastCommand="=";
             }
      else if(ae.getSource()==mul)
             {
              preRes=Double.parseDouble(result.getText());
              lastCommand="*";
              result.setText("0");
              }
      else if(ae.getSource()==plus)
              {
              preRes=Double.parseDouble(result.getText());
              lastCommand="+";
              result.setText("0");
              }

       }
 }

java chat program

CHAT SIMULATION USING JAVA
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * This applet simulates a network chat, in which the user chats with
 * someone over a network.  Here, there is no network.  The partner is
 * simulated by a thread that emits strings at random.  The point
 * of the simulation is to show how to use a separate thread for receiving
 * information.

 * The applet has an input box where the user enters messages.  When
 * the user presses return, the message is posted to a text area.  In
 * a real chat program, it would be transmitted over the network.
 * When a (simulated) message is received from the other side, it is
 * also posted to this text area. 

 * The partner thread is started the first time the user sends
 * a message.
 */

public class ChatSimulation extends JApplet implements ActionListener, Runnable {

   private static String[] incomingMessages = {  // Simulated messages from chat partner.
      "Say, how about those Mets.",
      "My favorite color is gray.  What's yours?",
      "In a World without Walls, who needs Windows?  "
      + "In a World without Fences, who needs Gates?",
      "An empty vessel makes the most noise.",
      "Can you tell me what a Thread is?",
      "Do you always follow style rules when you program?",
      "Sometimes, I really, really hate computers.",
      "Do you remember the Pythagorean theorem?",
      "Have you tried the GIMP image processing program?",
      "I was thinking, How come wrong numbers are never busy?",
      "Do you know Murphy's Law?  You should.",
      "Are you getting bored yet?",
      "Everything should be made as simple as possible -- but not simpler.",
      "The revolution will not be televised."
   };

   private JTextArea transcript;  // A text area that shows transmitted and
                                  // received messages.

   private JTextField input;  // A text-input box where the use enters
                              // outgoing messages.

   private Thread runner;    // The thread the simulated the incoming messages.

   private boolean running;  // This is set to true when the thread is created.
                             // when it becomes false, the thread should exit.
                             // It is set to false in the applet's stop() method.

   /**
    * Initialize the applet.
    */
   public void init() {
      JPanel content = new JPanel();
      content.setBackground(Color.LIGHT_GRAY);
      content.setLayout(new BorderLayout(3,3));
      content.setBorder(BorderFactory.createLineBorder(Color.GRAY,3));
      transcript = new JTextArea();
      transcript.setEditable(false);
      content.add(new JScrollPane(transcript),BorderLayout.CENTER);
      JPanel bottom = new JPanel();
      bottom.setBackground(Color.LIGHT_GRAY);
      bottom.setLayout(new BorderLayout(3,3));
      content.add(bottom,BorderLayout.SOUTH);
      input = new JTextField();
      input.setBackground(Color.WHITE);
      input.addActionListener(this);
      bottom.add(input,BorderLayout.CENTER);
      JButton send = new JButton("Send");
      send.addActionListener(this);
      bottom.add(send,BorderLayout.EAST);
      bottom.add(new JLabel("Text to send:"),BorderLayout.WEST);
      setContentPane(content);
   }

  
   /**
    *  This will be called when the user clicks the "Send" button or presses
    *  return in the text-input box.  It posts the contents of the input box
    *  to the transcript.  If the thread is not running, it creates and starts
    *  a new thread.
    */
   public void actionPerformed(ActionEvent evt) {
      postMessage("SENT: " + input.getText());
      input.selectAll();
      input.requestFocus();
      if (running == false) {
         runner = new Thread(this);
         running = true;
         runner.start();
      }
   }
  

   /**
    * Add a line of text to the transcript area.
    * @param message text to be added; two line feeds is added at the end.
    */
   private void postMessage(String message) {
      transcript.append(message + "\n\n");
         // The following line is a nasty kludge that was the only way I could find to force
         // the transcript to scroll so that the text that was just added is visible in
         // the window.  Without this, text can be added below the bottom of the visible area
         // of the transcript.
      transcript.setCaretPosition(transcript.getDocument().getLength());
   }


   /**
    * The run method just posts messages to the transcript
    * at random intervals of 2 to 10 seconds.
    */
   public void run() {
      //
      postMessage("RECEIVED: Hey, hello there! Nice to chat with you.");
      while (running) {
         try {
               // Wait a random time from 2000 to 10000 milliseconds.
            Thread.sleep( 2000 + (int)(8000*Math.random()) );
         }
         catch (InterruptedException e) {
         }
         int msgNum = (int)(Math.random() * incomingMessages.length);
         postMessage("RECEIVED: " + incomingMessages[msgNum]);
      }
   }
  

   /**
    * When applet is stopped, make sure that the thread will
    * terminate by setting running to false.
    */
   public void stop() {
      running = false;
      runner = null;
   }


} // end class ChatSimulation

Java Web BROWSER

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.net.URL;
/* <applet code="SimpleWebBrowser.Class" height=400 width=500></applet>  */
/**
 * Defines a simple web browser that can load web pages from
 * URLs specified by the user in a "Location" box.  Almost all
 * the functionality is provided automatically by the JEditorPane
 * class.  The program loads web pages synchronously and can hang
 * indefinitely while trying to load a page.  See
 * SimpleWebBrowserWithThread for an asynchronous version.
 * This class can be run as a standalone application and has
 * a nested class that can be run as an applet.  The applet
 * version can probably only read pages from the server from which
 * it was loaded.
 */
public class SimpleWebBrowser extends JPanel {

   /**
    * The main routine simply opens a window that shows a SimpleWebBrowser panel.
    */
   public static void main(String[] args) {
      JFrame window = new JFrame("SimpleWebBrowser");
      SimpleWebBrowser content = new SimpleWebBrowser();
      window.setContentPane(content);
      window.setSize(600,500);
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      window.setLocation( (screenSize.width - window.getWidth())/2,
            (screenSize.height - window.getHeight())/2 );
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setVisible(true);
   }
  
  
   /**
    * The public static class SimpleWebBrowser.Applet represents this program
    * as an applet.  The applet's init() method simply sets the content
    * pane of the applet to be a SimpleWebBrowser.  To use the applet on
    * a web page, use code="SimpleWebBrowser$Applet.class" as the name of
    * the class.
    */
   public static class Applet extends JApplet {
      public void init() {
         SimpleWebBrowser content = new SimpleWebBrowser();
         setContentPane( content );
      }
   }
  
  
   /**
    * The pane in which documents are displayed.
    */
   private JEditorPane editPane;
  
  
   /**
    * An input box where the user enters the URL of a document
    * to be loaded into the edit pane.  A value URL string has
    * to contain the substring "://".  If the string in the box
    * does not contain this substring, then "http://" is
    * prepended to the string.
    */
   private JTextField locationInput;
  
  
   /**
    * Defines a listener that responds when the user clicks on
    * a link in the document.
    */
   private class LinkListener implements HyperlinkListener {
      public void hyperlinkUpdate(HyperlinkEvent evt) {
         if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            loadURL(evt.getURL());
         }
      }
   }
  
  
   /**
    * Defines a listener that loads a new page when the user
    * clicks the "Go" button or presses return in the location
    * input box.
    */
   private class GoListener implements ActionListener {
      public void actionPerformed(ActionEvent evt) {
         URL url;
         try {
            String location = locationInput.getText().trim();
            if (location.length() == 0)
               throw new Exception();
            if (! location.contains("://"))
               location = "http://" + location;
            url = new URL(location);
         }
         catch (Exception e) {
            JOptionPane.showMessageDialog(SimpleWebBrowser.this,
                  "The Location input box does not\nccontain a legal URL.");
            return;
         }
         loadURL(url);
         locationInput.selectAll();
         locationInput.requestFocus();
      }
   }

  
   /**
    * Construct a panel that contains a JEditorPane in a JScrollPane,
    * with a tool bar that has a Location input box and a Go button.
    */
   public SimpleWebBrowser() {
     
      setBackground(Color.BLACK);
      setLayout(new BorderLayout(1,1));
      setBorder(BorderFactory.createLineBorder(Color.BLACK,1));

      editPane = new JEditorPane();
      editPane.setEditable(false);
      editPane.addHyperlinkListener(new LinkListener());
      add(new JScrollPane(editPane),BorderLayout.CENTER);
     
      JToolBar toolbar = new JToolBar();
      toolbar.setFloatable(false);
      add(toolbar,BorderLayout.NORTH);
      ActionListener goListener = new GoListener();
      locationInput = new JTextField("math.hws.edu/javanotes/index.html", 40);
      locationInput.addActionListener(goListener);
      JButton goButton = new JButton(" Go ");
      goButton.addActionListener(goListener);
      toolbar.add( new JLabel(" Location: "));
      toolbar.add(locationInput);
      toolbar.addSeparator(new Dimension(5,0));
      toolbar.add(goButton);

   }
  
  
   /**
    * Loads the document at the specified URL into the edit pane.
    */
   private void loadURL(URL url) {
      try {
         editPane.setPage(url);
      }
      catch (Exception e) {
         editPane.setContentType("text/plain");
         editPane.setText( "Sorry, the requested document was not found\n"
               +"or cannot be displayed.\n\nError:" + e);
      }
   }
  
}

RSS

Categories

Followers

Blog Archive

rTechIndia

RtechIndia->technology ahead

rtech

rtechindia

RtechIndia

Go rtechindia

Go rtechindia

RtechIndia

Wednesday 11 July 2012

JDBC

Introduction to JDB


Java started as an elegant and promising Web programming language. Thereafter, its transition to hard-core computing environment
 is a phenomenal feat. Apart from its significance on client-side programming, Java has been outstanding in developing mission-critical
 enterprise-scale applications and hence its immense contribution to server-side computing gets all round attention. Thus Java as
 a programming language for enterprise computing has been doing well for the past couple of years. As every enterprise includes a
 database, Sun Microsystems has to come with necessary features for making Java to shine in database programming as well.
 In this overview, we discuss about the role of Java Database Connectivity in accomplishing database programming with ease.



Database Programming with Java
Database Programming with Java

Java provides database programmers some distinct advantages, such as easy object to relational mapping, database independence
 and distributed computing. For languages, such as C++ and Smalltalk, there is a need for tools for mapping their objects to
 relational entities. Java provides an alternative to these tools that frees us from the proprietary interfaces associated with
 database programming. With the "write once, compile once, run anywhere" power that JDBC offers us, Java's database connectivity
 allows us to concentrate on the translation of relational data into objects instead of how we can get that data from the database.

A Java database application does not care what its database engine is. No matter how many times the database engine changes,
 the application itself need never change. In addition, a company can build a class library that maps its business objects to
 database entities in such a way that applications do not even know whether or not their objects are being stored in a database.

Java affects the way we distribute and maintain application. Currently a Web application allows user to download a bunch of flight
 information as an HTML page. While viewing the page for a particular flight, suppose some one makes a reservation for a seat on that
 flight and this process will not be available to the viewers as the page is just a copy of data from the database. To view the change
 that just occurred, the viewers again have to contact the database to get the latest data. If we reconstruct the same Web application
 using Java RMI to retrieve the data from a single flight object on the server, any number of users can view the data simultaneously and
 if there is any reservation or any change taking place, immediately the changes made to the data will be sent back to all the users and
 hence the users can avail the latest data at any time. Thus JDBC can combine with Java RMI to develop distributed enterprise-scale
 mission-critical three-tier database applications.
JDBC for Relational Databases

There are three main database technologies. They are relational, object and object-relational. A Java application can access any one
 of these database architectures. The overwhelming majority of today's database applications use relational databases. The JDBC API is
 thus heavily biased toward relational databases and their standard query language, SQL. Relational databases find and provide
 relationships between data and Java, as a object solution makes common cause with relational database technology due to the
 fact that object-oriented philosophy dictates that an object's behavior is inseparable from its data. In choosing the
 object-oriented reality of Java, we need to create a translation layer that maps the relational world into our object
 world. Thus with the goal of accessing relational databases, JDBC API specification has been defined by Sun Microsystems
 with the help of popular database vendors.

 What is JDBC?

JDBC is essentially an Application Programming Interface (API) for executing SQL statements, and extracting the results.
Using this API, we can write database clients, such as Java applets, servlets and Enterprise JavaBeans, that connect to a
relational database, such as Oracle, MySQL, Sybase, Informix, Ingres, PostgreSQL, or any other database that implements this API,
 execute SQL statements, and process the results extracted from the database.
JDBC Versions

JDBC 2.0 API is the latest version of JDBC API available in the java.sql package. The previous version focused primarily on basic
 database programming services such as creating connections, executing statements and prepared statements, running batch queries, etc.
 However, the current API supports batch updates, scrollable resultsets, transaction isolation, and the new SQL:1999 data types such as
 BLOB and CLOB in addition to the SQL2 data types.

JDBC 2.0 Optional Package API is available in the javax.sql package and is distributed with the enterprise edition of Java 2, that is J2EE.
 The optional package addresses Java Naming and Directory Interface (JNDI)-based data sources for managing connections, connection pooling,
 distributed transactions, and rowsets.
The Benefits of JDBC

The JDBC API provides a set of implementation-independent generic database access methods for the above mentioned SQL-compliant databases.
 JDBC abstracts much of the vendor-specific details and generalizes the most common database access functions. Thus resulted a set of classes
 and interfaces of the java.sql package that can be used with any database providing JDBC connectivity through a vendor-specific JDBC driver
 in a consistent way. Thus if our application conforms to the most commonly available database features, we should be able to reuse
 an application with another database simply by switching to a new JDBC driver. In other words, JDBC enables us to write applications
 that access relational databases without any thought as to which particular database we are using.

Also database connectivity is not just connecting to databases and executing statements. In an enterprise-level application environment
, there are some important requirements to be met, such as optimizing network resources by employing connection pooling, and implementing
distributed transactions. JDBC has all these features in accomplishing advanced database programming.
The JDBC Drivers

A database vendor typically provides a set of APIs for accessing the data managed by the database server. Popular database vendors have
 supplied some proprietary APIs for client access. Client applications written in native languages such as C and C++ can make these API
 calls for database access directly. The JDBC API provides a Java-language alternative to these vendor-specific APIs. Though this takes
 away the need to access vendor-specific native APIs for database access, the implementation of the JDBC layer still need to make these
 native calls for data access.

JDBC accomplishes its goals through a set of Java interfaces, each gets implemented differently by different vendors. The set of classes
 that implement the JDBC interfaces for a particular database engine is called a JDBC driver. Hence the necessity of a JDBC driver for
 each database server. In building a database application, we do not have to think about the implementation of these underlying classes
 at all as the whole point of using JDBC is to hide the specifics of each database and let us concentrate on our application.
 A JDBC driver is a middleware layer that translates the JDBC calls to the vendor-specific APIs. The Java VM uses the JDBC
 driver to translate the generalized JDBC calls into vendor-specific database calls that the database understands.

There are a number of approaches for connecting from our application to a database server via a database driver.

JDBC-ODBC Bridge - Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows
environment. ODBC is a Windows API standard for SQL and it is based on X/Open Call-Level Interface (CLI) specification, which is
a standard API for database access. CLI is intended to be vendor, platform, and database neutral. But ODBC API defines a set of
 functions for directly accessing the data without the need for embedding SQL statements in client applications coded in higher
 level languages.

The JDBC API is originally based on the ODBC API. Thus, it becomes feasible for the first category of JDBC drivers providing
a bridge between the JDBC API and the ODBC API. This bridge translates the standard JDBC calls to corresponding ODBC calls. The
 driver then delegates these calls to the data source. Here, the Java classes for the JDBC API and the JDBC-ODBC bridge are invoked
 within the client application process. Similarly, the ODBC layer executes in another process. This configuration requires the client
 application to have the JDBC-ODBC bridge API, the ODBC driver, and the native language level API, such as the OCI library for Oracle
 installed on each client machine.

Each data access call has to go through many layers, this approach for data access is inefficient for high-performance database
access requirements. Though this is not a preferred one, this has to be used in some situations for example, a Microsoft Access
2000 database can be only be accessed using the JDBC-ODBC bridge.

Part Java, Part Native Driver - This approach use a mixture of Java implementation and vendor-specific native APIs for data access.
 This one is a little bit faster than the earlier one. When a database call is made using JDBC, the driver translates the request
 into vendor-specific API calls. The database will process the request and send the results back through the API, which will forward
 them back to the JDBC driver. The JDBC driver will format the results to confirm to the JDBC standard and return them to the program.
 In this approach, the native JDBC driver, which is part Java and part native code, should be installed on each client along with the
 vendor-specific native language API. The native code uses vendor-specific protocols for communicating with the database. The improved
 efficiency makes this a preferred method over the use of the earlier one.

Intermediate Database Access Server This approach is based on intermediate (middleware) database servers with the ability to connect
multiple Java clients to multiple database servers. In this configuration, clients connect to various database servers via an intermediate
 server that acts as a gateway for multiple database servers. While the specific protocol used between clients and the intermediate server
 depends on the middleware server vendor, the intermediate server can use different native protocols to connect to different databases.
 The Java client application sends a JDBC call through a JDBC driver to the intermediate data access server. The middle-tier then handles
 the request using another driver, for example the above one, to complete the request. This is good because the intermediate server can
 abstract details of connections to database servers.

Pure Java Drivers - This a pure Java alternative to part Java, part native driver. These drivers convert the JDBC API calls to direct
network calls using vendor-specific networking by making direct socket connections with the database like Oracle Thin JDBC Driver.
 This is the most efficient method of accessing databases both in performance and development time. It also the simplest to deploy
 since there are no additional libraries or middleware to install. All major database vendors, such as Oracle, Sybase, and Microsoft,
 provide this type of drivers for their databases.
Alternatives to JDBC

There are two major alternatives to JDBC at present. They are ODBC and SQLJ, a non-approved Java standard for database access.

Without JDBC, only disparate, proprietary database access solutions exist. These solutions force the developer to build a layer
 of abstraction on top of them in order to create database-independent code. The ODBC solution provide this universal abstraction
 layer for languages, such as C and C++, and popular developmental tools, such as Delphi, PowerBuilder, and VisualBasic. But ODBC
 can not enjoy the platform independence of Java as ODBC is restricted to Windows platform. On using JDBC, the server application
 can pick the database at run time based on which client is connecting. Thus JDBC facilitates to change the database just by
 changing the JDBC URL and driver name without adding any new code.

connect to database using java



Connecting to a MySQL Database in Java


    

In java we have been provided with some classes and APIs with which we can make use of the database as we like.
Database plays as very important role in the programming because we have to store the values somewhere in the back- end.
So, we should know how we can manipulate the data in the database with the help of java,  instead of going to database for
a manipulation. We have many database provided like Oracle, MySQL etc. We are using MySQL for developing this application.

In this section, you will learn how to connect the MySQL database with the Java file. Firstly, we need to establish a
connection between MySQL and Java files with the help of MySQL driver .  Now we will make our  account in MySQL database
so that we can get connected to the database. After establishing a connection  we can access or retrieve data form MySQL
database. We are going to make a program on connecting to a MySQL database, after going through this program you will be
 able to establish a connection on your own PC.

Description of program:

This program establishes the connection between MySQL database and java files with the help of various types of APIs interfaces
and methods. If connection is established then it shows "Connected to the database" otherwise it will displays a message "Disconnected
from database".

Description of code:

Connection:
This is an interface in  java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and
java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver):
This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that
 matches class with given string.

DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like:

    url: - Database url where stored or created your database
  userName: - User name of MySQL
  password: -Password of MySQL

con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the database.

printStackTrace():
The method is used to show error messages. If the connection is not established then exception is thrown and print the message.

import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
  System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "jdbctutorial";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root";
  String password = "root";
  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
}

java calculator

 JAVA CALCULATOR

/**
  This is a simple calculator program can any one take and use.

   */
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200></applet>
public class Calculator extends JApplet {
   public void init() {
      CalculatorPanel calc=new CalculatorPanel();
      getContentPane().add(calc);
      }
   }

   class CalculatorPanel extends JPanel implements ActionListener {
      JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
      static JTextField result=new JTextField("0",45);
      static String lastCommand=null;
      JOptionPane p=new JOptionPane();
      double preRes=0,secVal=0,res;

      private static void assign(String no)
        {
         if((result.getText()).equals("0"))
            result.setText(no);
          else if(lastCommand=="=")
           {
            result.setText(no);
            lastCommand=null;
           }
          else
            result.setText(result.getText()+no);
         }

      public CalculatorPanel() {
         setLayout(new BorderLayout());
         result.setEditable(false);
         result.setSize(300,200);
         add(result,BorderLayout.NORTH);
         JPanel panel=new JPanel();
         panel.setLayout(new GridLayout(4,4));

         n7=new JButton("7");
         panel.add(n7);
         n7.addActionListener(this);
         n8=new JButton("8");
         panel.add(n8);
         n8.addActionListener(this);
         n9=new JButton("9");
         panel.add(n9);
         n9.addActionListener(this);
         div=new JButton("/");
         panel.add(div);
         div.addActionListener(this);

         n4=new JButton("4");
         panel.add(n4);
         n4.addActionListener(this);
         n5=new JButton("5");
         panel.add(n5);
         n5.addActionListener(this);
         n6=new JButton("6");
         panel.add(n6);
         n6.addActionListener(this);
         mul=new JButton("*");
         panel.add(mul);
         mul.addActionListener(this);

         n1=new JButton("1");
         panel.add(n1);
         n1.addActionListener(this);
         n2=new JButton("2");
         panel.add(n2);
         n2.addActionListener(this);
         n3=new JButton("3");
         panel.add(n3);
         n3.addActionListener(this);
         minus=new JButton("-");
         panel.add(minus);
         minus.addActionListener(this);

         dot=new JButton(".");
         panel.add(dot);
         dot.addActionListener(this);
         n0=new JButton("0");
         panel.add(n0);
         n0.addActionListener(this);
         
         equal=new JButton("=");
         panel.add(equal);
         equal.addActionListener(this);
         plus=new JButton("+");
         panel.add(plus);
         plus.addActionListener(this);
         add(panel,BorderLayout.CENTER);
      }
      public void actionPerformed(ActionEvent ae)
         {
      if(ae.getSource()==n1) assign("1");
      else if(ae.getSource()==n2) assign("2");
      else if(ae.getSource()==n3) assign("3");
      else if(ae.getSource()==n4) assign("4");
      else if(ae.getSource()==n5) assign("5");
      else if(ae.getSource()==n6) assign("6");
      else if(ae.getSource()==n7) assign("7");
      else if(ae.getSource()==n8) assign("8");
      else if(ae.getSource()==n9) assign("9");
      else if(ae.getSource()==n0) assign("0");
     
      else if(ae.getSource()==dot)
            {
             if(((result.getText()).indexOf("."))==-1)
                result.setText(result.getText()+".");
           }
      else if(ae.getSource()==minus)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="-";
             result.setText("0");
             }
      else if(ae.getSource()==div)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="/";
             result.setText("0");
             }
      else if(ae.getSource()==equal)
             {
             secVal=Double.parseDouble(result.getText());
             if(lastCommand.equals("/"))
                  res=preRes/secVal;
             else if(lastCommand.equals("*"))
                  res=preRes*secVal;
             else if(lastCommand.equals("-"))
                  res=preRes-secVal;
             else if(lastCommand.equals("+"))
                  res=preRes+secVal;
             result.setText(" "+res);
             lastCommand="=";
             }
      else if(ae.getSource()==mul)
             {
              preRes=Double.parseDouble(result.getText());
              lastCommand="*";
              result.setText("0");
              }
      else if(ae.getSource()==plus)
              {
              preRes=Double.parseDouble(result.getText());
              lastCommand="+";
              result.setText("0");
              }

       }
 }

java chat program

CHAT SIMULATION USING JAVA
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * This applet simulates a network chat, in which the user chats with
 * someone over a network.  Here, there is no network.  The partner is
 * simulated by a thread that emits strings at random.  The point
 * of the simulation is to show how to use a separate thread for receiving
 * information.

 * The applet has an input box where the user enters messages.  When
 * the user presses return, the message is posted to a text area.  In
 * a real chat program, it would be transmitted over the network.
 * When a (simulated) message is received from the other side, it is
 * also posted to this text area. 

 * The partner thread is started the first time the user sends
 * a message.
 */

public class ChatSimulation extends JApplet implements ActionListener, Runnable {

   private static String[] incomingMessages = {  // Simulated messages from chat partner.
      "Say, how about those Mets.",
      "My favorite color is gray.  What's yours?",
      "In a World without Walls, who needs Windows?  "
      + "In a World without Fences, who needs Gates?",
      "An empty vessel makes the most noise.",
      "Can you tell me what a Thread is?",
      "Do you always follow style rules when you program?",
      "Sometimes, I really, really hate computers.",
      "Do you remember the Pythagorean theorem?",
      "Have you tried the GIMP image processing program?",
      "I was thinking, How come wrong numbers are never busy?",
      "Do you know Murphy's Law?  You should.",
      "Are you getting bored yet?",
      "Everything should be made as simple as possible -- but not simpler.",
      "The revolution will not be televised."
   };

   private JTextArea transcript;  // A text area that shows transmitted and
                                  // received messages.

   private JTextField input;  // A text-input box where the use enters
                              // outgoing messages.

   private Thread runner;    // The thread the simulated the incoming messages.

   private boolean running;  // This is set to true when the thread is created.
                             // when it becomes false, the thread should exit.
                             // It is set to false in the applet's stop() method.

   /**
    * Initialize the applet.
    */
   public void init() {
      JPanel content = new JPanel();
      content.setBackground(Color.LIGHT_GRAY);
      content.setLayout(new BorderLayout(3,3));
      content.setBorder(BorderFactory.createLineBorder(Color.GRAY,3));
      transcript = new JTextArea();
      transcript.setEditable(false);
      content.add(new JScrollPane(transcript),BorderLayout.CENTER);
      JPanel bottom = new JPanel();
      bottom.setBackground(Color.LIGHT_GRAY);
      bottom.setLayout(new BorderLayout(3,3));
      content.add(bottom,BorderLayout.SOUTH);
      input = new JTextField();
      input.setBackground(Color.WHITE);
      input.addActionListener(this);
      bottom.add(input,BorderLayout.CENTER);
      JButton send = new JButton("Send");
      send.addActionListener(this);
      bottom.add(send,BorderLayout.EAST);
      bottom.add(new JLabel("Text to send:"),BorderLayout.WEST);
      setContentPane(content);
   }

  
   /**
    *  This will be called when the user clicks the "Send" button or presses
    *  return in the text-input box.  It posts the contents of the input box
    *  to the transcript.  If the thread is not running, it creates and starts
    *  a new thread.
    */
   public void actionPerformed(ActionEvent evt) {
      postMessage("SENT: " + input.getText());
      input.selectAll();
      input.requestFocus();
      if (running == false) {
         runner = new Thread(this);
         running = true;
         runner.start();
      }
   }
  

   /**
    * Add a line of text to the transcript area.
    * @param message text to be added; two line feeds is added at the end.
    */
   private void postMessage(String message) {
      transcript.append(message + "\n\n");
         // The following line is a nasty kludge that was the only way I could find to force
         // the transcript to scroll so that the text that was just added is visible in
         // the window.  Without this, text can be added below the bottom of the visible area
         // of the transcript.
      transcript.setCaretPosition(transcript.getDocument().getLength());
   }


   /**
    * The run method just posts messages to the transcript
    * at random intervals of 2 to 10 seconds.
    */
   public void run() {
      //
      postMessage("RECEIVED: Hey, hello there! Nice to chat with you.");
      while (running) {
         try {
               // Wait a random time from 2000 to 10000 milliseconds.
            Thread.sleep( 2000 + (int)(8000*Math.random()) );
         }
         catch (InterruptedException e) {
         }
         int msgNum = (int)(Math.random() * incomingMessages.length);
         postMessage("RECEIVED: " + incomingMessages[msgNum]);
      }
   }
  

   /**
    * When applet is stopped, make sure that the thread will
    * terminate by setting running to false.
    */
   public void stop() {
      running = false;
      runner = null;
   }


} // end class ChatSimulation

Java Web BROWSER

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.net.URL;
/* <applet code="SimpleWebBrowser.Class" height=400 width=500></applet>  */
/**
 * Defines a simple web browser that can load web pages from
 * URLs specified by the user in a "Location" box.  Almost all
 * the functionality is provided automatically by the JEditorPane
 * class.  The program loads web pages synchronously and can hang
 * indefinitely while trying to load a page.  See
 * SimpleWebBrowserWithThread for an asynchronous version.
 * This class can be run as a standalone application and has
 * a nested class that can be run as an applet.  The applet
 * version can probably only read pages from the server from which
 * it was loaded.
 */
public class SimpleWebBrowser extends JPanel {

   /**
    * The main routine simply opens a window that shows a SimpleWebBrowser panel.
    */
   public static void main(String[] args) {
      JFrame window = new JFrame("SimpleWebBrowser");
      SimpleWebBrowser content = new SimpleWebBrowser();
      window.setContentPane(content);
      window.setSize(600,500);
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      window.setLocation( (screenSize.width - window.getWidth())/2,
            (screenSize.height - window.getHeight())/2 );
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setVisible(true);
   }
  
  
   /**
    * The public static class SimpleWebBrowser.Applet represents this program
    * as an applet.  The applet's init() method simply sets the content
    * pane of the applet to be a SimpleWebBrowser.  To use the applet on
    * a web page, use code="SimpleWebBrowser$Applet.class" as the name of
    * the class.
    */
   public static class Applet extends JApplet {
      public void init() {
         SimpleWebBrowser content = new SimpleWebBrowser();
         setContentPane( content );
      }
   }
  
  
   /**
    * The pane in which documents are displayed.
    */
   private JEditorPane editPane;
  
  
   /**
    * An input box where the user enters the URL of a document
    * to be loaded into the edit pane.  A value URL string has
    * to contain the substring "://".  If the string in the box
    * does not contain this substring, then "http://" is
    * prepended to the string.
    */
   private JTextField locationInput;
  
  
   /**
    * Defines a listener that responds when the user clicks on
    * a link in the document.
    */
   private class LinkListener implements HyperlinkListener {
      public void hyperlinkUpdate(HyperlinkEvent evt) {
         if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            loadURL(evt.getURL());
         }
      }
   }
  
  
   /**
    * Defines a listener that loads a new page when the user
    * clicks the "Go" button or presses return in the location
    * input box.
    */
   private class GoListener implements ActionListener {
      public void actionPerformed(ActionEvent evt) {
         URL url;
         try {
            String location = locationInput.getText().trim();
            if (location.length() == 0)
               throw new Exception();
            if (! location.contains("://"))
               location = "http://" + location;
            url = new URL(location);
         }
         catch (Exception e) {
            JOptionPane.showMessageDialog(SimpleWebBrowser.this,
                  "The Location input box does not\nccontain a legal URL.");
            return;
         }
         loadURL(url);
         locationInput.selectAll();
         locationInput.requestFocus();
      }
   }

  
   /**
    * Construct a panel that contains a JEditorPane in a JScrollPane,
    * with a tool bar that has a Location input box and a Go button.
    */
   public SimpleWebBrowser() {
     
      setBackground(Color.BLACK);
      setLayout(new BorderLayout(1,1));
      setBorder(BorderFactory.createLineBorder(Color.BLACK,1));

      editPane = new JEditorPane();
      editPane.setEditable(false);
      editPane.addHyperlinkListener(new LinkListener());
      add(new JScrollPane(editPane),BorderLayout.CENTER);
     
      JToolBar toolbar = new JToolBar();
      toolbar.setFloatable(false);
      add(toolbar,BorderLayout.NORTH);
      ActionListener goListener = new GoListener();
      locationInput = new JTextField("math.hws.edu/javanotes/index.html", 40);
      locationInput.addActionListener(goListener);
      JButton goButton = new JButton(" Go ");
      goButton.addActionListener(goListener);
      toolbar.add( new JLabel(" Location: "));
      toolbar.add(locationInput);
      toolbar.addSeparator(new Dimension(5,0));
      toolbar.add(goButton);

   }
  
  
   /**
    * Loads the document at the specified URL into the edit pane.
    */
   private void loadURL(URL url) {
      try {
         editPane.setPage(url);
      }
      catch (Exception e) {
         editPane.setContentType("text/plain");
         editPane.setText( "Sorry, the requested document was not found\n"
               +"or cannot be displayed.\n\nError:" + e);
      }
   }
  
}