Pages

Monday, April 19, 2010

Fetch data from MS Access using java

Database

JDBCExample


import  java.sql.*;

public class JDBCExample
{

private String url,user,pwd;
private Connection conn;
private Statement stmt;
private PreparedStatement pstmt;
private ResultSet rs;

public JDBCExample()
{
}

public void testDatabase()
{
int i=0;
String sql;

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception sqe)
{
System.out.println("Error loading driver");
}
url="jdbc:odbc:emp";



pwd ="";
user="";

try
{
conn=DriverManager.getConnection(url,user,pwd);
}
catch(SQLException sqe)
{
System.out.println("Error getting connection to database");
}

try
{
stmt=conn.createStatement();
}
catch(SQLException sqee)
{
System.out.println("Error creating statement");
}

try
{
rs=stmt.executeQuery("select * from emp");
}
catch(SQLException qexe)
{
System.out.println("Error executing query");
}





/*try
{
while(rs.next())
{
int code=rs.getInt(1);
System.out.println("code="+code);
}
}

catch(SQLException e)
{
System.out.println("error to trversing");
}*/

try
{
while(rs.next())
{
String name=rs.getString(1);
int rollno=rs.getInt(2);
String add=rs.getString(3);
int phoneno=rs.getInt(4);
System.out.println("name="+name);
System.out.println("rollno="+rollno);
System.out.println("add="+add);
System.out.println("phoneno="+phoneno);
System.out.println("      ");

}


}

catch(SQLException es)
{
System.out.println("error to traversing");
}


try
{
rs.close();
conn.close();
}
catch(SQLException sqxe)
{
System.out.println("Error closing result set or connection");
}
}

public static void main(String args[])
{
JDBCExample jdbcex=new JDBCExample();
jdbcex.testDatabase();

}
}

Friday, April 16, 2010

Insert Data into Access Database using JSP

Project Tree

Database


registration.jsp

<%--
    Document   : display
    Created on : 13 Apr, 2010, 9:54:48 AM
    Author     : Bhasker
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>registration</title>
    </head>
    <body>
        <h1>registration form</h1>

        <form name="registration1" action="display.jsp" method="POST">
        <table border="1">

            <thead>
                <tr>
                    <th>enter information</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>name</td>
                    <td><input type="text" name="n1" value="" size="30" /></td>
                </tr>
                <tr>
                    <td>city</td>
                    <td><input type="text" name="c1" value="" size="30" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="submit" name="b1" /></td>
                </tr>
            </tbody>
        </table>

</form>


    </body>

</html>


display.jsp

<%-- 
    Document   : display
    Created on : 14 Apr, 2010, 2:38:06 PM
    Author     : Bhasker
--%>
<%@page import ="java.sql.*"%>
<%@page import =" java.util.*"%>
<%@page import =" java. io.*"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>registration record!</h1>


        <%
              try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           Connection con=DriverManager.getConnection("jdbc:odbc:reg");
           Statement st=con.createStatement();
           PreparedStatement pst=con.prepareStatement("insert into registration(name,city) values(?, ?)");
           pst.clearParameters();
           
           pst.setString(1,request.getParameter("n1"));
           pst.setString(2,request.getParameter("c1") );
         int i=  pst.executeUpdate();
         if(i>0)
             {
         out.println("Record Saved");

         ResultSet rs=st.executeQuery("Select * from registration");
         out.print("<br/>");

         out.print("<table border=4>");
           while(rs.next())
           {
               out.print("<tr bgcolor=pink>");
               out.print("<td>");
           out.print(rs.getString(1));
           out.print("</td>");
           out.print("<td>");
           out.print(rs.getString(2));
           out.print("</td>");
out.print("</tr>");

           }
         out.print("</table>");
         }
         else
             {out.println("Record Not Saved");}
           
      

        }
        catch(Exception e)
        {}
        finally {
            out.close();
        }

        %>

    </body>

</html>

Thursday, April 15, 2010

WAP to demonstrate database connectivity jsp with MS Access with the help of servlet.

Project Tree

index.jsp



<%-- 
    Document   : index
    Created on : Mar 23, 2010, 11:50:05 AM
    Author     : Administrator
--%>


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>


        <form action="NewServlet">
            <input type="submit" value="Show Record" />
        </form>
    </body>
</html>

NewServlet.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
/**
 *
 * @author Administrator
 */
public class NewServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           Connection con=DriverManager.getConnection("jdbc:odbc:test");
           Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select * from employee");
           while(rs.next())
           {
           out.print(rs.getString(1));
           out.print(rs.getString(2)); 
           out.print(rs.getString(3));
         
           }

            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet NewServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet NewServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        }
        catch(Exception ee)
        {}
        finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

WAP to demonstrate database connectivity jsp with MS Access with the help of beans.

Project file Tree 



DataBase





index.java



<%@page language="Java" import="java.sql.*" %>
 <jsp:useBean id="db" scope="request" class="SQLBean.DbBean" />
 <jsp:setProperty name="db" property="*" />
  <%!
          ResultSet rs = null ;

         int i;
%>


<HTML>
<HEAD><TITLE>DataBase Search</TITLE></HEAD>
<BODY>
<h2> Results from </h2>
<hr>
<br><br>
<table border="1">

<%
   db.connect();

try {
          rs = db.execSQL("select * from EMPLOYEE");
          i = db.updateSQL("UPDATE employee set empid = 'e005' where empname='ravi'");
        
        }catch(SQLException e) {
              throw new ServletException("Your query is not working", e);      
              }

         %>
<tr>
    <th>Emp ID</th>
    <th>NAME</th>
    <th>ADDRESS</th>
</tr>
<%      
      while(rs.next()) {
%>
<tr>

<td><%= rs.getString("empid") %></td>
<td><%= rs.getString("empname") %></td>
<td><%= rs.getString("empadd") %></td>

</tr>


<%
}
%>
<%  db.close();

%>

</table>

</body>

<HTML>




DBBean.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package SQLBean;
import java.sql.*;
//import java.io.*;
/**
 *
 * @author Administrator
 */
public class DbBean {
String dbURL = "jdbc:odbc:test";
  String dbDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
  private Connection dbCon;

  public DbBean(){
       super();      
       }

  public boolean connect() throws ClassNotFoundException,SQLException{
          Class.forName(dbDriver);
          dbCon = DriverManager.getConnection(dbURL);
          return true;
        }
  public void close() throws SQLException{
        dbCon.close();
       }

  public ResultSet execSQL(String sql) throws SQLException{

                    Statement s = dbCon.createStatement();
                    ResultSet r = s.executeQuery(sql);
                    return (r == null) ? null : r;
                    }

  public int updateSQL(String sql) throws SQLException{                  
                   Statement s = dbCon.createStatement();
                   int r = s.executeUpdate(sql);
                   return (r == 0) ? 0 : r;
                }
}






Tuesday, April 6, 2010

OOS Programming Lab-(MCA-451)



List of Programs

  1. WAP to show the implementation of function overloading.
  2. WAP to Implement abstract classes.
  3. WAP to implement function overriding.
  4. WAP to implement WAP to implement final keyword.
  5. WAP to show exception handling.
  6. WAP to implement user defined exceptions.
  7. WAP to implement super keyword.
  8. WAP to implement applet life cycle.
  9. WAP to implement command line argument.
  10. WAP to implement a package.
  11. Write a program to implement various visibility mode.
  12. WAP to draw a line.
  13. WAP to draw a square.
  14. WAP to draw a rectangle.
  15. WAP to draw a hut.
  16. WAP to input data from keyboard.
  17. WAP of Button using Swing.
  18. WAP of Tabbed panes using Swing
  19. WAP of Grid Layout.
  20. WAP of Border Layout.
  21. WAP to demonstrate menu.
  22. WAP to demonstrate database connectivity java with MS Access.
  23. WAP to demonstrate database connectivity jsp with MS Access with the help of beans.
  24. WAP to demonstrate database connectivity jsp with MS Access with the help of servlet.
  25. WAP to demonstrate database connectivity jsp with MS Access.

Wednesday, February 24, 2010

Object Oriented Systems UNIT 1 (NOTES)

OO Analysis and Design-
OO Analysis - examines requirements from the perspective of the classes and objects found in the vocabulary of the problem domain. In other words, the world (of the system) is modelled in terms of objects and classes.
OO Design - OO decomposition and a notation for depicting models of the system under development. Structures are developed whereby sets of objects collaborate to provide the behaviours that satisfy the requirements of the problem.

Object Oriented Analysis-

  • Analyze the domain problem
  • Describe the process systems
  • Identify the objects
  • Specify attributes
  • Defining operations
  • Inter-object Communication
Identifying Object-

• Objects can be:
  • External Entity (e.g., other systems, devices, people) that produce or consume information to be used by system
  • Things (e.g., reports, displays, letters, signals) that are part of information domain for the problem
  • Places (e.g., book’s room) that establish the context of the problem and the overall function of the system.
  • Organizational units (e.g., division, group, team, department) that are relevant to an application,
  • Transaction (e.g., loan, take course, buy, order).
Objects –
  •  Object is an abstraction of something in a problem domain, reflecting the capabilities of the system to  keep information about it, interact with it, or both.
  •  Objects are entities in a software system which represents instances of real-world and system entities.


Object Class-
         Class is a description of a set of objects that share the same attributes, operations, methods, relationship and semantics.
         Object classes are templates for objects. They may be used to create objects.
         An object represents a particular instance of a class.

Term of objects-

         Attribute: data items that define object. An attributes is a data value held by the object in a class. Example- Color, weight and model year are attributes of Car objects.
         Operation: function in a class that combines to form behavior of class. Each operation has a target object as an implicit argument.
         Methods: the actual implementation of procedure (the body of code that is executed in response to a request from other objects in the system).




Encapsulation and Data Hiding-
         Packaging related data and operations together is called encapsulation.
         Data hiding: hides the internal data from external by methods (interface).

Encapsulation-

l      private attributes and methods are encapsulated within the class, they cannot be seen by clients of the class
l      public methods define the interface that the class provides to its clients



Object communication-
         Objects communicate with each other by sending messages
        a message is a method call from a message-sending object to a message-receiving object
        a message consists of
         an object reference which indicates the message receiver
         a method name (corresponding to a method of the receiver), and
         parameters (corresponding to the arguments of the calling method)
        a message-receiving object is a server to a message-sending object, and the message-sending object is a client of the server






Message Passing

Inheritance-
         Object classes may inherit attributes and services from other object classes.
         Inheritance represents the generalization of a class.

A generalisation hierarchy- Generalization and inheritance are powerful abstractions for sharing similarities among classes while preserving their differences. Generalization is the relationship between a class and one or more refined version of it. The class being refined is called its super class and each refined version is called a sub class. The notation for generalization is a triangle connecting a super class to its sub class.









Multiple inheritance-

         Rather than inheriting the attributes and services from a single parent class, a system which supports multiple inheritance allows object classes to inherit from several super-classes
         Can lead to semantic conflicts where attributes/services with the same name in different super-classes have different semantics
         Makes class hierarchy reorganisation more complex



Advantages of inheritance-

         It is an abstraction mechanism which may be used to classify entities
         It is a reuse mechanism at both the design and the programming level
         The inheritance graph is a source of organisational knowledge about domains and systems

Problems with inheritance-
         Object classes are not self-contained. they cannot be understood without reference to their super-classes
         Designers have a tendency to reuse the inheritance graph created during
         analysis. Can lead to significant inefficiency
         The inheritance graphs of analysis, design and implementation have different functions and should be separately maintained


Link:
·         A link is a physical or conceptual connection between object instances
·         A link is an instance of an association.
Objects Association-
         Modeling an association between two classes means that there is some sort of relationship between objects of each class that may be connected.
         An association describes a group of links with common structure and common semantics.
         Although associations are modeled as bidirectional they do not have to be implemented in both directions.
         Association may be binary, ternary or higher order.


Object aggregation-
         Aggregation model shows how classes which are collections are composed of other classes Similar to the part-of relationship in semantic data models.
         Aggregation is a strong form of association in which an aggregate object is made of components.
         A single aggregate object may have several parts; each part-whole relationship is treated as a separate aggregation in order to emphasize the similarity to association.


Polymorphism-
         The ability of different objects to perform the appropriate method in response to the same message is known as polymorphism.
         the selection of the appropriate method depends on the class used to create the object



Candidate Keys: A candidate key is a minimal set of attributes that uniquely identifies an object or link by minimal, we mean that you can not be discard an attribute from the candidate key and still all objects and link. A class or association may have one or more candidate keys, each of which may have different combinations and attributes. The object id is always a candidate key for a class. One or more combinations of related objects are candidate key for associations.


Example of candidate objects-

Just a Line management wishes to increase security, both in their building and on site, without antagonizing their employees. They would also like to prevent people who are not part of the company from using the Just a Line car park.
It has been decide to issue identity cards to all employees, which they are expected to wear while on the Just a Line site. The cards records the name, department and number of the member of staff, and permit access to the Just a Line  car park.
A barrier and a card reader are placed at the entrance to the car park. The driver of an approaching car insert his or her numbered card in the card reader, which then checks that the card number is known to the Just a Line system. If the card is recognized, the reader sends a signal to raise the barrier and the car is able to enter the car park.
At the exit, there is also a barrier, which is raised when a car wishes to leave the car park.
When there are no spaces in the car park a sign at the entrance display “Full” and is only switched off when a car leaves.
Special visitor’s cards, which record a number and the current date, also permit access to the car park. Visitor’s cards may be sent out in advance, or collected from reception. All visitor’s cards must be returned to reception when the visitor leaves Just a Line.



Candidate objects:
Just a Line              management                          security                              building
Site                         employee                                people                               company
car park                  card                                        name                                  department
number                   member of staff                     access                                barrier
card reader             entrance                                  driver                                car
system                   signal                                       exit                                    space
sign                        visitor                                     reception

Candidate objects’ rejection-

         duplicates: if two or more objects are simply different names for the same thing.
         irrelevant: objects which exists in the problem domain, but which are not intended.
         vague: when considering words carefully it sometimes becomes clear that they do not have a price meaning and cannot be the basis of a useful in the system.
         general: the meaning is too broad.
         attributes: as the attribute of objects.
         associations: actually represents the relationships between objects.
         roles: sometimes objects referred to by the role they play in a particular part of the system.


Rejected Candidate objects





Rest Objects-
Car park                                   Staff Card                       Visitor’s card
Employee                                 Entrance                          exit                        
card reader                               barrier                              Full sign
space                                        sensor                              car


Object Relationship-






Multiplicity-
  • Multiplicity specifies how many instances of one class may relate to single instances of one class may relate to single instances of associated classes.
  • Multiplicity contains the number of related classes.
  • Multiplicity depends on assumptions and how you define the boundaries of a problem.

Role Name-
  • A role is one end of association.
  • A binary association has two roles, each of which may have a role name.
  • A role name is a name that uniquely identifies one end of association 





Metadata- Metadata is data that describe other data. For example, the definition of a class is metadata. Many real world applications have metadata, such as parts, catalogs, blue-prints and dictionaries.

Constraints- Constraints are functional relationship between entities of an object model. The term entity includes objects, classes, attributes, links and association. A constraint restricts the values that entries can assume. Examples include: No employee’s salary can exceed the salary of the employee’s boss.





Followers