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

Sunday, 29 April 2012

RSS feed by XML using CSS

Improving an XML feed display through CSS and XSLT

XML feeds, though useful, are boring to look at in a browser because they are simple XML files. It's possible though to make them easier on the eye, and in this article we'll look at two ways of doing that. First, we'll use simple CSS properties to format each XML node, and then we'll use a little more complex but much more powerful XSL transformation.


Introduction

XML feeds have become a common way for people to keep updated on their favorite websites, no matter what specification they follow (RSS, Atom, etc.). XML files suffer though from poor usability by nature as they are not friendly to look at in the browser. Your feed handler (e.g. FeedDemon, FeedReader, NewsGator, etc.) will, of course, display them in a nicely formatted way, but in this article we'll see two ways to spice up their boring browser display:

    Using CSS definitions on the individual notes
    Applying an XSL Tranformation file

For our example, we'll assume that we are serving feeds in RSS 2.0 format, but the principles discussed should apply for any type of XML feed. You can rest assured that this type of formatting will not change the way your readers use your feeds. I first got this idea after reading a blog entry by Pete Freitag.
First, the original XML feed

So, Let's a take a look at a typical RSS 2.0 feed: an example of a possible "latest articles" feed for this site:
<?xml version="1.0" encoding="iso-8859-1"?>

<?xml-stylesheet type="text/css" href="itemof.css" ?>
     <rss version="2.0">
     <channel xmlns:html="http://www.w3.org/1999/xhtml">
   
      <html:hr/>
   
         <title>rtechinsane.in</title>
        <html:hr/>
         <link>http://www.rtechinsane.in</link>
         <description>The latest articles from rtechinsane.in</description>
         <language>en-us</language>
         <copyright>Copyright 2012 rtechinsane.in</copyright>
         <docs>http://blogs.law.harvard.edu/tech/rss/</docs>
         <lastBuildDate>Mon, 23 April 2012 00:00:00 MST</lastBuildDate>
        
         <item>
             <title>Improving an XML feed display through CSS and XSLT</title>
            <photo>
         <html:img src="img.jpg" width="80" height="80" />Flannel Bush
      </photo>
             <description>XML feeds, though useful, are boring to look at in a browser because they are simple XML files. It's possible though to make them easier on the eye, and in this article we'll look at two ways of doing that. First, we'll use simple CSS properties to format each XML node, and then we'll use a little more complex but much more powerful XSL transformation.</description>
             <pubDate>Sun, 06 Mar 2005 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=24</link>
         </item>
        

         <item>
             <title>Identity fields in Oracle and SQL Server</title>
            <photo>
         <html:img src="img.jpg" width="80" height="90" />Flannel Bush
      </photo>
             <description>While it may be relatively easy to create an incrementing and unique identifier inside a table in SQL Server, things get tricky with Oracle. In this article, we'll see the differences between the two databases and offer a way of solving the problem.</description>
             <author>email@yoursite.com </author>
        <pubDate>Mon, 17 Mar 2003 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=23</link>
         </item>

        
         <item>
             <title>Exporting Word files to HTML</title>
            <photo>
         <html:img src="img.jpg" width="80" height="80" />Flannel Bush
      </photo>
             <description>In this article we will first discuss the case for and against using Word as your HTML editor. Then we will see how to properly save a Word file to smaller, more compact HTML files. Third and last, we will see how to do this through code, and possibly create a batch process for converting numerous Word files to HTML at once.</description>
             <author>email@yoursite.com </author>
             <pubDate>Wed, 05 Mar 2003 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=22</link>
         </item>

        
     </channel>
     </rss>

We are not doing anything new here. We are following the RSS 2.0 specification to create this feed: a channel wrapper with its feed properties, including as many item nodes as we want of the latest posts (with their own properties). Here's what this feed looks like through the browser:

XML Feed with no formatting

Basic yes, friendly to look at no. So, let's see how to improve this display.
Formatting through CSS

The principle here is that since a feed is made up of XML nodes, we can apply CSS formatting on them to change the way they display in the browser. First we need to add the CSS reference inside the XML file. This can be a full URL with the domain, or simply a website relative address:
1     <?xml version="1.0" encoding="ISO-8859-1" ?>
2     <?xml-stylesheet type="text/css" href="/includes/css/rssfeed.css" ?>
3     <rss version="2.0">

Under channel, we have the mandatory title, which is the feed title. To edit the display of this node to a bigger text size we can simply add this to our CSS:
1     channel title {
2         font-size:140%;
3     }


We can follow this principle to format the rest of the notes. One issue that we have to keep in mind is that if there is more than one node named title, then they will all inherit the same properties. In the example shown, the second tag will also display with font size 140%. To fix this, we will need to create a separate CSS property for it and change the size:
1     channel item title {
2         font-size:100%;
3     }

Our feeds most often contain properties that we may not necessarily want to have them display in our improved version. So. we can group all nodes that we want to hide and change their display property to hidden. The order of the nodes in the XML file will be maintained, unless you can figure out a way to change this through CSS.

Here is a complete CSS file as an example:
1     channel link, channel language, channel copyright, channel managingEditor, channel webMaster, channel docs, channel lastBuildDate {
2         display:none;
3     }
4     rss {
5         font-family:Verdana, Arial, Helvetica, sans-serif;
6         font-size:0.7em;
7         line-height:130%;
8         margin:1em;
9     }
10     /* HEADER */
11     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
12     channel title {
13         display:block;
14         padding:0.4em 0.2em;
15         color:#FFF;
16         border-bottom:1px solid black;
17         font-weight:bold;
18         font-size:140%;
19         background-color:#4483C7;
20     }
21     channel description {
22         display:block;
23         float:left;
24         font-size:130%;
25         font-weight:bold;
26         margin:0.5em;
27     }
28     /* CONTENT */
29     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
30     channel item {
31         background-color:#FFFFEE;
32         border:1px solid #538620;
33         clear:both;
34         display:block;
35         padding:0 0 0.5em;
36         margin:1em;
37     }
38     channel item title {
39         background-color:#538620;
40         border-bottom-width:0;
41         color:#FFF;
42         display:block;
43         font-size:110%;
44         font-weight:bold;
45         margin:0;
46         padding:0.3em 0.5em;
47     }
48     channel item description {
49         display: block;
50         float:none;
51         margin:0;
52         text-align: left;
53         padding:0.2em 0.5em 0.4em;
54         color: black;
55         font-size:100%;
56         font-weight:normal;
57     }
58     channel item link {
59         color:#666;
60         display:block;
61         font-size:86%;
62         padding:0 0.5em;
63     }
64     channel item pubDate {
65         color:#666;
66         display:block;
67         font-size:86%;
68         padding:0 0.5em;
69     }

   

Here's a screenshot of the resulting output:

XML feed with CSS formatting

PL/SQl cursors

What are Cursors?

A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set.

There are two types of cursors in PL/SQL:
Implicit cursors:
These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed.


Explicit cursors:

They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row.
Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.



Implicit Cursors:

When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements.

Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN.

For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected.
When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected.

The status of the cursor for each of these attributes are defined in the below table.
Attributes
   

Return Value
   

Example

%FOUND
   

The return value is TRUE, if the DML statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT ….INTO statement return at least one row.
   

SQL%FOUND

The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE do not affect row and if SELECT….INTO statement do not return a row.

%NOTFOUND
   

The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE at least one row and if SELECT ….INTO statement return at least one row.
   

SQL%NOTFOUND

The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect even one row and if SELECT ….INTO statement does not return a row.

%ROWCOUNT
   

Return the number of rows affected by the DML operations INSERT, DELETE, UPDATE, SELECT
   

SQL%ROWCOUNT

For Example: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:

DECLARE  var_rows number(5);

BEGIN

  UPDATE employee

  SET salary = salary + 1000;

  IF SQL%NOTFOUND THEN

    dbms_output.put_line('None of the salaries where updated');

  ELSIF SQL%FOUND THEN

    var_rows := SQL%ROWCOUNT;

    dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');

  END IF;

END;


In the above PL/SQL Block, the salaries of all the employees in the ‘employee’ table are updated. If none of the employee’s salary are updated we get a message 'None of the salaries where updated'. Else we get a message like for example, 'Salaries for 1000 employees are updated' if there are 1000 rows in ‘employee’ table.

PL/SQL iterative

Iterative Statements in PL/SQL

An iterative control Statements are used when we want to repeat the execution of one or more statements for specified number of times. These are similar to those in

There are three types of loops in PL/SQL:
• Simple Loop
• While Loop
• For Loop
1) Simple Loop

A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates. An EXIT condition must be specified in the loop, otherwise the loop will get into an infinite number of iterations. When the EXIT condition is satisfied the process exits from the loop.
The General Syntax to write a Simple Loop is:

LOOP

   statements;

   EXIT;

   {or EXIT WHEN condition;}

END LOOP;

These are the important steps to be followed while using Simple Loop.

1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without WHEN condition, the statements in the loop is executed only once.
2) While Loop

A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. The condition is evaluated at the beginning of each iteration. The iteration continues until the condition becomes false.
The General Syntax to write a WHILE LOOP is:

WHILE <condition>

 LOOP statements;

END LOOP;

Important steps to follow when executing a while loop:

1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done oftenly.
3) FOR Loop

A FOR LOOP is used to execute a set of statements for a predetermined number of times. Iteration occurs between the start and end integer values given. The counter is always incremented by 1. The loop exits when the counter reachs the value of the end integer.

The General Syntax to write a FOR LOOP is:

FOR counter IN val1..val2

  LOOP statements;

END LOOP;

    val1 - Start integer value.
    val2 - End integer value.

Important steps to follow when executing a while loop:

1) The counter variable is implicitly declared in the declaration section, so it's not necessary to declare it explicity.
2) The counter variable is incremented by 1 and does not need to be incremented explicitly.
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done oftenly.

NOTE: The above Loops are explained with a example when dealing with Explicit Cursors.

Saturday, 28 April 2012

PL/SQL exceptions

Exception Handling


In this section we will discuss about the following,
1) What is Exception Handling.
2) Structure of Exception Handling.
3) Types of Exception Handling.

1) What is Exception Handling?

PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting abruptly. When an exception occurs a messages which explains its cause is recieved.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message

By Handling the exceptions we can ensure a PL/SQL block does not exit abruptly.

2) Structure of Exception Handling.

The General Syntax for coding the exception section
 DECLARE
   Declaration section 
 BEGIN 
   Exception section 
 EXCEPTION 
 WHEN ex_name1 THEN 
    -Error handling statements 
 WHEN ex_name2 THEN 
    -Error handling statements 
 WHEN Others THEN 
   -Error handling statements 
END; 
General PL/SQL statments can be used in the Exception Block.
When an exception is raised, Oracle searches for an appropriate exception handler in the exception section. For example in the above example, if the error raised is 'ex_name1 ', then the error is handled according to the statements under it. Since, it is not possible to determine all the possible runtime errors during testing fo the code, the 'WHEN Others' exception is used to manage the exceptions that are not explicitly handled. Only one exception can be raised in a Block and the control does not return to the Execution Section after the error is handled.
If there are nested PL/SQL blocks like this.
 DELCARE
   Declaration section 
 BEGIN
    DECLARE
      Declaration section 
    BEGIN 
      Execution section 
    EXCEPTION 
      Exception section 
    END; 
 EXCEPTION
   Exception section 
 END; 
In the above case, if the exception is raised in the inner block it should be handled in the exception block of the inner PL/SQL block else the control moves to the Exception block of the next upper PL/SQL Block. If none of the blocks handle the exception the program ends abruptly with an error.

3) Types of Exception.

There are 3 types of Exceptions.
a) Named System Exceptions
b) Unnamed System Exceptions
c) User-defined Exceptions

a) Named System Exceptions

System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule. There are some system exceptions which are raised frequently, so they are pre-defined and given a name in Oracle which are known as Named System Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.
Named system exceptions are:
1) Not Declared explicitly,
2) Raised implicitly when a predefined Oracle error occurs,
3) caught by referencing the standard name within an exception-handling routine.
Exception Name Reason Error Number
CURSOR_ALREADY_OPEN When you open a cursor that is already open. ORA-06511
INVALID_CURSOR When you perform an invalid operation on a cursor like closing a cursor, fetch data from a cursor that is not opened. ORA-01001
NO_DATA_FOUND When a SELECT...INTO clause does not return any row from a table. ORA-01403
TOO_MANY_ROWS When you SELECT or fetch more than one row into a record or variable. ORA-01422
ZERO_DIVIDE When you attempt to divide a number by zero. ORA-01476
For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code to handle the exception as given below.
BEGIN 
  Execution section
EXCEPTION 
WHEN NO_DATA_FOUND THEN 
 dbms_output.put_line ('A SELECT...INTO did not return any row.'); 
 END; 

b) Unnamed System Exceptions

Those system exception for which oracle does not provide a name is known as unamed system exception. These exception do not occur frequently. These Exceptions have a code and an associated message.
There are two ways to handle unnamed sysyem exceptions:
1. By using the WHEN OTHERS exception handler, or
2. By associating the exception code to a name and using it as a named exception.
We can assign a name to unnamed system exceptions using a Pragma called EXCEPTION_INIT.
EXCEPTION_INIT will associate a predefined Oracle error number to a programmer_defined exception name.
Steps to be followed to use unnamed system exceptions are
• They are raised implicitly.
• If they are not handled in WHEN Others they must be handled explicity.
• To handle the exception explicity, they must be declared using Pragma EXCEPTION_INIT as given above and handled referecing the user-defined exception name in the exception section.
The general syntax to declare unnamed system exception using EXCEPTION_INIT is:
DECLARE 
   exception_name EXCEPTION; 
   PRAGMA 
   EXCEPTION_INIT (exception_name, Err_code); 
BEGIN 
Execution section
EXCEPTION
  WHEN exception_name THEN
     handle the exception
END;
For Example: Lets consider the product table and order_items table from sql joins.
Here product_id is a primary key in product table and a foreign key in order_items table.
If we try to delete a product_id from the product table when it has child records in order_id table an exception will be thrown with oracle code number -2292.
We can provide a name to this exception and handle it in the exception section as given below.
 DECLARE 
  Child_rec_exception EXCEPTION; 
  PRAGMA 
   EXCEPTION_INIT (Child_rec_exception, -2292); 
BEGIN 
  Delete FROM product where product_id= 104; 
EXCEPTION 
   WHEN Child_rec_exception 
   THEN Dbms_output.put_line('Child records are present for this product_id.'); 
END; 
/ 

c) User-defined Exceptions

Apart from sytem exceptions we can explicity define exceptions based on business rules. These are known as user-defined exceptions.
Steps to be followed to use user-defined exceptions:
• They should be explicitly declared in the declaration section.
• They should be explicitly raised in the Execution Section.
• They should be handled by referencing the user-defined exception name in the exception section.
For Example: Lets consider the product table and order_items table from sql joins to explain user-defined exception.
Lets create a business rule that if the total no of units of any particular product sold is more than 20, then it is a huge quantity and a special discount should be provided.
DECLARE 
  huge_quantity EXCEPTION; 
  CURSOR product_quantity is 
  SELECT p.product_name as name, sum(o.total_units) as units
  FROM order_tems o, product p
  WHERE o.product_id = p.product_id; 
  quantity order_tems.total_units%type; 
  up_limit CONSTANT order_tems.total_units%type := 20; 
  message VARCHAR2(50); 
BEGIN 
  FOR product_rec in product_quantity LOOP 
    quantity := product_rec.units;
     IF quantity > up_limit THEN 
      message := 'The number of units of product ' || product_rec.name ||  
                 ' is more than 20. Special discounts should be provided. 
   Rest of the records are skipped. '
     RAISE huge_quantity; 
     ELSIF quantity < up_limit THEN 
      v_message:= 'The number of unit is below the discount limit.'; 
     END IF; 
     dbms_output.put_line (message); 
  END LOOP; 
 EXCEPTION 
   WHEN huge_quantity THEN 
     dbms_output.put_line (message); 
 END; 
/ 

RAISE_APPLICATION_ERROR ( )

RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the user-defined error messages along with the error number whose range is in between -20000 and -20999.
Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous transactions which are not committed within the PL/SQL Block are rolled back automatically (i.e. change due to INSERT, UPDATE, or DELETE statements).
RAISE_APPLICATION_ERROR raises an exception but does not handle it.
RAISE_APPLICATION_ERROR is used for the following reasons,
a) to create a unique id for an user-defined exception.
b) to make the user-defined exception look like an Oracle error.
The General Syntax to use this procedure is:
RAISE_APPLICATION_ERROR (error_number, error_message); 

• The Error number must be between -20000 and -20999
• The Error_message is the message you want to display when the error occurs. Steps to be folowed to use RAISE_APPLICATION_ERROR procedure:
1. Declare a user-defined exception in the declaration section.
2. Raise the user-defined exception based on a specific business rule in the execution section.
3. Finally, catch the exception and link the exception to a user-defined error number in RAISE_APPLICATION_ERROR.
Using the above example we can display a error message using RAISE_APPLICATION_ERROR.
DECLARE
  huge_quantity EXCEPTION; 
  CURSOR product_quantity is 
  SELECT p.product_name as name, sum(o.total_units) as units
  FROM order_tems o, product p
  WHERE o.product_id = p.product_id; 
  quantity order_tems.total_units%type; 
  up_limit CONSTANT order_tems.total_units%type := 20; 
  message VARCHAR2(50); 
BEGIN 
  FOR product_rec in product_quantity LOOP 
    quantity := product_rec.units;
     IF quantity > up_limit THEN 
        RAISE huge_quantity; 
     ELSIF quantity < up_limit THEN 
      v_message:= 'The number of unit is below the discount limit.'; 
     END IF; 
     Dbms_output.put_line (message); 
  END LOOP; 
 EXCEPTION 
   WHEN huge_quantity THEN 
 raise_application_error(-2100, 'The number of unit is above the discount limit.');
 END; 
/ 

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

Sunday, 29 April 2012

RSS feed by XML using CSS

Improving an XML feed display through CSS and XSLT

XML feeds, though useful, are boring to look at in a browser because they are simple XML files. It's possible though to make them easier on the eye, and in this article we'll look at two ways of doing that. First, we'll use simple CSS properties to format each XML node, and then we'll use a little more complex but much more powerful XSL transformation.


Introduction

XML feeds have become a common way for people to keep updated on their favorite websites, no matter what specification they follow (RSS, Atom, etc.). XML files suffer though from poor usability by nature as they are not friendly to look at in the browser. Your feed handler (e.g. FeedDemon, FeedReader, NewsGator, etc.) will, of course, display them in a nicely formatted way, but in this article we'll see two ways to spice up their boring browser display:

    Using CSS definitions on the individual notes
    Applying an XSL Tranformation file

For our example, we'll assume that we are serving feeds in RSS 2.0 format, but the principles discussed should apply for any type of XML feed. You can rest assured that this type of formatting will not change the way your readers use your feeds. I first got this idea after reading a blog entry by Pete Freitag.
First, the original XML feed

So, Let's a take a look at a typical RSS 2.0 feed: an example of a possible "latest articles" feed for this site:
<?xml version="1.0" encoding="iso-8859-1"?>

<?xml-stylesheet type="text/css" href="itemof.css" ?>
     <rss version="2.0">
     <channel xmlns:html="http://www.w3.org/1999/xhtml">
   
      <html:hr/>
   
         <title>rtechinsane.in</title>
        <html:hr/>
         <link>http://www.rtechinsane.in</link>
         <description>The latest articles from rtechinsane.in</description>
         <language>en-us</language>
         <copyright>Copyright 2012 rtechinsane.in</copyright>
         <docs>http://blogs.law.harvard.edu/tech/rss/</docs>
         <lastBuildDate>Mon, 23 April 2012 00:00:00 MST</lastBuildDate>
        
         <item>
             <title>Improving an XML feed display through CSS and XSLT</title>
            <photo>
         <html:img src="img.jpg" width="80" height="80" />Flannel Bush
      </photo>
             <description>XML feeds, though useful, are boring to look at in a browser because they are simple XML files. It's possible though to make them easier on the eye, and in this article we'll look at two ways of doing that. First, we'll use simple CSS properties to format each XML node, and then we'll use a little more complex but much more powerful XSL transformation.</description>
             <pubDate>Sun, 06 Mar 2005 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=24</link>
         </item>
        

         <item>
             <title>Identity fields in Oracle and SQL Server</title>
            <photo>
         <html:img src="img.jpg" width="80" height="90" />Flannel Bush
      </photo>
             <description>While it may be relatively easy to create an incrementing and unique identifier inside a table in SQL Server, things get tricky with Oracle. In this article, we'll see the differences between the two databases and offer a way of solving the problem.</description>
             <author>email@yoursite.com </author>
        <pubDate>Mon, 17 Mar 2003 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=23</link>
         </item>

        
         <item>
             <title>Exporting Word files to HTML</title>
            <photo>
         <html:img src="img.jpg" width="80" height="80" />Flannel Bush
      </photo>
             <description>In this article we will first discuss the case for and against using Word as your HTML editor. Then we will see how to properly save a Word file to smaller, more compact HTML files. Third and last, we will see how to do this through code, and possibly create a batch process for converting numerous Word files to HTML at once.</description>
             <author>email@yoursite.com </author>
             <pubDate>Wed, 05 Mar 2003 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=22</link>
         </item>

        
     </channel>
     </rss>

We are not doing anything new here. We are following the RSS 2.0 specification to create this feed: a channel wrapper with its feed properties, including as many item nodes as we want of the latest posts (with their own properties). Here's what this feed looks like through the browser:

XML Feed with no formatting

Basic yes, friendly to look at no. So, let's see how to improve this display.
Formatting through CSS

The principle here is that since a feed is made up of XML nodes, we can apply CSS formatting on them to change the way they display in the browser. First we need to add the CSS reference inside the XML file. This can be a full URL with the domain, or simply a website relative address:
1     <?xml version="1.0" encoding="ISO-8859-1" ?>
2     <?xml-stylesheet type="text/css" href="/includes/css/rssfeed.css" ?>
3     <rss version="2.0">

Under channel, we have the mandatory title, which is the feed title. To edit the display of this node to a bigger text size we can simply add this to our CSS:
1     channel title {
2         font-size:140%;
3     }


We can follow this principle to format the rest of the notes. One issue that we have to keep in mind is that if there is more than one node named title, then they will all inherit the same properties. In the example shown, the second tag will also display with font size 140%. To fix this, we will need to create a separate CSS property for it and change the size:
1     channel item title {
2         font-size:100%;
3     }

Our feeds most often contain properties that we may not necessarily want to have them display in our improved version. So. we can group all nodes that we want to hide and change their display property to hidden. The order of the nodes in the XML file will be maintained, unless you can figure out a way to change this through CSS.

Here is a complete CSS file as an example:
1     channel link, channel language, channel copyright, channel managingEditor, channel webMaster, channel docs, channel lastBuildDate {
2         display:none;
3     }
4     rss {
5         font-family:Verdana, Arial, Helvetica, sans-serif;
6         font-size:0.7em;
7         line-height:130%;
8         margin:1em;
9     }
10     /* HEADER */
11     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
12     channel title {
13         display:block;
14         padding:0.4em 0.2em;
15         color:#FFF;
16         border-bottom:1px solid black;
17         font-weight:bold;
18         font-size:140%;
19         background-color:#4483C7;
20     }
21     channel description {
22         display:block;
23         float:left;
24         font-size:130%;
25         font-weight:bold;
26         margin:0.5em;
27     }
28     /* CONTENT */
29     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
30     channel item {
31         background-color:#FFFFEE;
32         border:1px solid #538620;
33         clear:both;
34         display:block;
35         padding:0 0 0.5em;
36         margin:1em;
37     }
38     channel item title {
39         background-color:#538620;
40         border-bottom-width:0;
41         color:#FFF;
42         display:block;
43         font-size:110%;
44         font-weight:bold;
45         margin:0;
46         padding:0.3em 0.5em;
47     }
48     channel item description {
49         display: block;
50         float:none;
51         margin:0;
52         text-align: left;
53         padding:0.2em 0.5em 0.4em;
54         color: black;
55         font-size:100%;
56         font-weight:normal;
57     }
58     channel item link {
59         color:#666;
60         display:block;
61         font-size:86%;
62         padding:0 0.5em;
63     }
64     channel item pubDate {
65         color:#666;
66         display:block;
67         font-size:86%;
68         padding:0 0.5em;
69     }

   

Here's a screenshot of the resulting output:

XML feed with CSS formatting

PL/SQl cursors

What are Cursors?

A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set.

There are two types of cursors in PL/SQL:
Implicit cursors:
These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed.


Explicit cursors:

They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row.
Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.



Implicit Cursors:

When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements.

Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN.

For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected.
When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected.

The status of the cursor for each of these attributes are defined in the below table.
Attributes
   

Return Value
   

Example

%FOUND
   

The return value is TRUE, if the DML statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT ….INTO statement return at least one row.
   

SQL%FOUND

The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE do not affect row and if SELECT….INTO statement do not return a row.

%NOTFOUND
   

The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE at least one row and if SELECT ….INTO statement return at least one row.
   

SQL%NOTFOUND

The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect even one row and if SELECT ….INTO statement does not return a row.

%ROWCOUNT
   

Return the number of rows affected by the DML operations INSERT, DELETE, UPDATE, SELECT
   

SQL%ROWCOUNT

For Example: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:

DECLARE  var_rows number(5);

BEGIN

  UPDATE employee

  SET salary = salary + 1000;

  IF SQL%NOTFOUND THEN

    dbms_output.put_line('None of the salaries where updated');

  ELSIF SQL%FOUND THEN

    var_rows := SQL%ROWCOUNT;

    dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');

  END IF;

END;


In the above PL/SQL Block, the salaries of all the employees in the ‘employee’ table are updated. If none of the employee’s salary are updated we get a message 'None of the salaries where updated'. Else we get a message like for example, 'Salaries for 1000 employees are updated' if there are 1000 rows in ‘employee’ table.

PL/SQL iterative

Iterative Statements in PL/SQL

An iterative control Statements are used when we want to repeat the execution of one or more statements for specified number of times. These are similar to those in

There are three types of loops in PL/SQL:
• Simple Loop
• While Loop
• For Loop
1) Simple Loop

A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates. An EXIT condition must be specified in the loop, otherwise the loop will get into an infinite number of iterations. When the EXIT condition is satisfied the process exits from the loop.
The General Syntax to write a Simple Loop is:

LOOP

   statements;

   EXIT;

   {or EXIT WHEN condition;}

END LOOP;

These are the important steps to be followed while using Simple Loop.

1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without WHEN condition, the statements in the loop is executed only once.
2) While Loop

A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. The condition is evaluated at the beginning of each iteration. The iteration continues until the condition becomes false.
The General Syntax to write a WHILE LOOP is:

WHILE <condition>

 LOOP statements;

END LOOP;

Important steps to follow when executing a while loop:

1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done oftenly.
3) FOR Loop

A FOR LOOP is used to execute a set of statements for a predetermined number of times. Iteration occurs between the start and end integer values given. The counter is always incremented by 1. The loop exits when the counter reachs the value of the end integer.

The General Syntax to write a FOR LOOP is:

FOR counter IN val1..val2

  LOOP statements;

END LOOP;

    val1 - Start integer value.
    val2 - End integer value.

Important steps to follow when executing a while loop:

1) The counter variable is implicitly declared in the declaration section, so it's not necessary to declare it explicity.
2) The counter variable is incremented by 1 and does not need to be incremented explicitly.
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done oftenly.

NOTE: The above Loops are explained with a example when dealing with Explicit Cursors.

Saturday, 28 April 2012

PL/SQL exceptions

Exception Handling


In this section we will discuss about the following,
1) What is Exception Handling.
2) Structure of Exception Handling.
3) Types of Exception Handling.

1) What is Exception Handling?

PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting abruptly. When an exception occurs a messages which explains its cause is recieved.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message

By Handling the exceptions we can ensure a PL/SQL block does not exit abruptly.

2) Structure of Exception Handling.

The General Syntax for coding the exception section
 DECLARE
   Declaration section 
 BEGIN 
   Exception section 
 EXCEPTION 
 WHEN ex_name1 THEN 
    -Error handling statements 
 WHEN ex_name2 THEN 
    -Error handling statements 
 WHEN Others THEN 
   -Error handling statements 
END; 
General PL/SQL statments can be used in the Exception Block.
When an exception is raised, Oracle searches for an appropriate exception handler in the exception section. For example in the above example, if the error raised is 'ex_name1 ', then the error is handled according to the statements under it. Since, it is not possible to determine all the possible runtime errors during testing fo the code, the 'WHEN Others' exception is used to manage the exceptions that are not explicitly handled. Only one exception can be raised in a Block and the control does not return to the Execution Section after the error is handled.
If there are nested PL/SQL blocks like this.
 DELCARE
   Declaration section 
 BEGIN
    DECLARE
      Declaration section 
    BEGIN 
      Execution section 
    EXCEPTION 
      Exception section 
    END; 
 EXCEPTION
   Exception section 
 END; 
In the above case, if the exception is raised in the inner block it should be handled in the exception block of the inner PL/SQL block else the control moves to the Exception block of the next upper PL/SQL Block. If none of the blocks handle the exception the program ends abruptly with an error.

3) Types of Exception.

There are 3 types of Exceptions.
a) Named System Exceptions
b) Unnamed System Exceptions
c) User-defined Exceptions

a) Named System Exceptions

System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule. There are some system exceptions which are raised frequently, so they are pre-defined and given a name in Oracle which are known as Named System Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.
Named system exceptions are:
1) Not Declared explicitly,
2) Raised implicitly when a predefined Oracle error occurs,
3) caught by referencing the standard name within an exception-handling routine.
Exception Name Reason Error Number
CURSOR_ALREADY_OPEN When you open a cursor that is already open. ORA-06511
INVALID_CURSOR When you perform an invalid operation on a cursor like closing a cursor, fetch data from a cursor that is not opened. ORA-01001
NO_DATA_FOUND When a SELECT...INTO clause does not return any row from a table. ORA-01403
TOO_MANY_ROWS When you SELECT or fetch more than one row into a record or variable. ORA-01422
ZERO_DIVIDE When you attempt to divide a number by zero. ORA-01476
For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code to handle the exception as given below.
BEGIN 
  Execution section
EXCEPTION 
WHEN NO_DATA_FOUND THEN 
 dbms_output.put_line ('A SELECT...INTO did not return any row.'); 
 END; 

b) Unnamed System Exceptions

Those system exception for which oracle does not provide a name is known as unamed system exception. These exception do not occur frequently. These Exceptions have a code and an associated message.
There are two ways to handle unnamed sysyem exceptions:
1. By using the WHEN OTHERS exception handler, or
2. By associating the exception code to a name and using it as a named exception.
We can assign a name to unnamed system exceptions using a Pragma called EXCEPTION_INIT.
EXCEPTION_INIT will associate a predefined Oracle error number to a programmer_defined exception name.
Steps to be followed to use unnamed system exceptions are
• They are raised implicitly.
• If they are not handled in WHEN Others they must be handled explicity.
• To handle the exception explicity, they must be declared using Pragma EXCEPTION_INIT as given above and handled referecing the user-defined exception name in the exception section.
The general syntax to declare unnamed system exception using EXCEPTION_INIT is:
DECLARE 
   exception_name EXCEPTION; 
   PRAGMA 
   EXCEPTION_INIT (exception_name, Err_code); 
BEGIN 
Execution section
EXCEPTION
  WHEN exception_name THEN
     handle the exception
END;
For Example: Lets consider the product table and order_items table from sql joins.
Here product_id is a primary key in product table and a foreign key in order_items table.
If we try to delete a product_id from the product table when it has child records in order_id table an exception will be thrown with oracle code number -2292.
We can provide a name to this exception and handle it in the exception section as given below.
 DECLARE 
  Child_rec_exception EXCEPTION; 
  PRAGMA 
   EXCEPTION_INIT (Child_rec_exception, -2292); 
BEGIN 
  Delete FROM product where product_id= 104; 
EXCEPTION 
   WHEN Child_rec_exception 
   THEN Dbms_output.put_line('Child records are present for this product_id.'); 
END; 
/ 

c) User-defined Exceptions

Apart from sytem exceptions we can explicity define exceptions based on business rules. These are known as user-defined exceptions.
Steps to be followed to use user-defined exceptions:
• They should be explicitly declared in the declaration section.
• They should be explicitly raised in the Execution Section.
• They should be handled by referencing the user-defined exception name in the exception section.
For Example: Lets consider the product table and order_items table from sql joins to explain user-defined exception.
Lets create a business rule that if the total no of units of any particular product sold is more than 20, then it is a huge quantity and a special discount should be provided.
DECLARE 
  huge_quantity EXCEPTION; 
  CURSOR product_quantity is 
  SELECT p.product_name as name, sum(o.total_units) as units
  FROM order_tems o, product p
  WHERE o.product_id = p.product_id; 
  quantity order_tems.total_units%type; 
  up_limit CONSTANT order_tems.total_units%type := 20; 
  message VARCHAR2(50); 
BEGIN 
  FOR product_rec in product_quantity LOOP 
    quantity := product_rec.units;
     IF quantity > up_limit THEN 
      message := 'The number of units of product ' || product_rec.name ||  
                 ' is more than 20. Special discounts should be provided. 
   Rest of the records are skipped. '
     RAISE huge_quantity; 
     ELSIF quantity < up_limit THEN 
      v_message:= 'The number of unit is below the discount limit.'; 
     END IF; 
     dbms_output.put_line (message); 
  END LOOP; 
 EXCEPTION 
   WHEN huge_quantity THEN 
     dbms_output.put_line (message); 
 END; 
/ 

RAISE_APPLICATION_ERROR ( )

RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the user-defined error messages along with the error number whose range is in between -20000 and -20999.
Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous transactions which are not committed within the PL/SQL Block are rolled back automatically (i.e. change due to INSERT, UPDATE, or DELETE statements).
RAISE_APPLICATION_ERROR raises an exception but does not handle it.
RAISE_APPLICATION_ERROR is used for the following reasons,
a) to create a unique id for an user-defined exception.
b) to make the user-defined exception look like an Oracle error.
The General Syntax to use this procedure is:
RAISE_APPLICATION_ERROR (error_number, error_message); 

• The Error number must be between -20000 and -20999
• The Error_message is the message you want to display when the error occurs. Steps to be folowed to use RAISE_APPLICATION_ERROR procedure:
1. Declare a user-defined exception in the declaration section.
2. Raise the user-defined exception based on a specific business rule in the execution section.
3. Finally, catch the exception and link the exception to a user-defined error number in RAISE_APPLICATION_ERROR.
Using the above example we can display a error message using RAISE_APPLICATION_ERROR.
DECLARE
  huge_quantity EXCEPTION; 
  CURSOR product_quantity is 
  SELECT p.product_name as name, sum(o.total_units) as units
  FROM order_tems o, product p
  WHERE o.product_id = p.product_id; 
  quantity order_tems.total_units%type; 
  up_limit CONSTANT order_tems.total_units%type := 20; 
  message VARCHAR2(50); 
BEGIN 
  FOR product_rec in product_quantity LOOP 
    quantity := product_rec.units;
     IF quantity > up_limit THEN 
        RAISE huge_quantity; 
     ELSIF quantity < up_limit THEN 
      v_message:= 'The number of unit is below the discount limit.'; 
     END IF; 
     Dbms_output.put_line (message); 
  END LOOP; 
 EXCEPTION 
   WHEN huge_quantity THEN 
 raise_application_error(-2100, 'The number of unit is above the discount limit.');
 END; 
/