naeem ahmed mahotonaeem ahmed mahoto email: [email protected] general notes java javascript...

57
Department of Software Engineering Mehran University of Engineering and Technology Jamshoro, Sindh, Pakistan Naeem Ahmed Mahoto Email: [email protected] General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts

Upload: others

Post on 11-Mar-2020

21 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Department of Software Engineering Mehran University of Engineering and Technology Jamshoro, Sindh, Pakistan

Naeem Ahmed Mahoto Email: naeemmahoto@gmail .com

General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts

Page 2: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

GENERAL CONCEPTS OLE (Object Linking and Embedding) - software that allows a user to create a file in one application and incorporate it into another, while retaining the original file format and association to the program that created it. OEM (Original Equipment Manufacturer) - a company that assembles computers and other hardware devices. Operating System (OS) - operating system provides an environment for a user to run other programs. Multithreading -The running of several processes in rapid sequence (multitasking) within a single program Multitasking – Allows several different activities to occur concurrently on the computer. Process based Multi-Tasking - In which several different processes are running on the same computer. Thread Based Multi-Tasking - Type of Multitasking which allows different several parts of the same program to run concurrently. Multiprocessing – Two or more connected and roughly equal processing units each carry out one or more processes; each processing unit works on a different set of instructions or on different parts of the same process. Multicasting - The process of sending a message simultaneously to more than one destination on a network Parallel processing - A method of processing that can run only on a type of computer containing two or more processors running simultaneously. Parallel processing differs from multiprocessing in the way a task is distributed over the available processors. In multiprocessing, a process might be divided up into sequential blocks, with one processor managing access to a database, another analyzing the data, and a third handling graphical output to the screen. Bug – The errors in the execution of a program Procedure – A set of instructions that perform some specific task, procedures do not return any value. Function - A set of instructions that perform some specific task, functions return some value. Package - A set of related procedures or functions that are compiled and stored together in the data dictionary. Debugger - A debugger is the integrated tool that helps to find program bugs Stored Procedure/Function – The procedures that has been stored in the library cache. Multiprogramming - A form of processing in which a computer holds more than one program in memory and works on them in round-robin fashion—that is, by sharing out the processor’s time so that each program receives some attention some of the time. Unstructured programming -The main program directly operates on global data.

Page 3: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Procedural programming - A procedure call is used to invoke the procedure. After the sequence is processed, flow of control proceeds right after the position where the call was made.

Modular programming - The main program coordinates calls to procedures in separate modules and hands over appropriate data as parameters.

Data Structure – The organization of data such as storage of data Socket - The basic object used by applications to perform most network communications is called a socket. Sockets were designed so that most network communications between applications could be performed in the same way that these same applications would read and write files. ActiveX Control An ActiveX control is a set of functionality packaged in a COM (Component Object Model) object. This COM object is self-contained, although it does not have the ability to run by itself. An ActiveX control can only run within a ActiveX container, such as a Visual C++ or Visual Basic application. Events - Events are notification messages that are sent from the control to the container application. Dynamic link libraries (DLL)

Page 4: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

DLLs are similar to library modules in that they both contain sets of functionality that have been packaged for use by applications. The difference is when the applications link to the library. With a library module (LIB), the application is linked to the functionality in the library during the compile and build process. The functionality contained in the library file becomes part of the application executable file. With a DLL, the application links to the functionality in the library file when the application is run. The library file remains a separate file that is referenced and called by the application. ActiveX Control An ActiveX control is a software component that can be plugged into many different programs and used as if it were a native part of the program. ActiveX Data Objects (ADO) - ADO presents the Visual C++ programmer with new challenges in database programming, while still keeping the functionality familiar. ADO was to create a control that could be used to provide data access and control in Web pages, caching the data records on the client. Part of the reason for this goal was to allow a Web browser user to access an entire set of data records, without having to pull down each individual record, one at a time, to navigate and make changes to the records. Single Document Interface (SDI) - An SDI application is a document-centric application that can only work with one document at a time, and can only work with one type of document. Multiple Document Interface (MDI) - MDI applications not only enable the user to work on multiple documents at the same time, but also MDI applications can allow the user to work on multiple types of documents. An MDI application uses a window-in-a-window style.

OBJECT ORIENTED CONCEPTS Object Oriented Programming is a way of organizing programs and offers a new and powerful way to cope the complexity of procedural languages with objects. Its goal is clearer, more reliable, more easily maintained programs. Object Oriented Programming increases the reusability of class / objects. Objects of the program interact by sending messages to each other.

Page 5: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Encapsulation - In object-oriented programming, the packaging of attributes (properties) and functionality (methods or behaviors) to create an object that is essentially a “black box” and it ensures that the object providing service can prevent other objects from manipulating its data or procedures directly.

JAVA (J2SDK 1.4.0)

IDE: 1- Integrated Development Environment where you can develop, run, test and debug your applications. 2- Integrated Development Environment a very friendly environment for

creating and editing your source code and compiling & debugging your programs.

LANGUAGE: It is a set of sequential instructions. COMPILER: It converts the whole program in Machine language. INTERPRETER: It converts the program in Machine language but instruction by instruction.

JVM: Java Virtual Machine is an interpreter and converts the Java Byte Code (JBC) in machine language according to the machine (Intel, Motorola, Sparc, etc.) which supports JAVA.

JDK Java Development Kit contains Java Virtual Machine and Class Libraries.

CLASS Class consist of data and methods.

JVM

Class Libraries

JDK DATA

METHODS CLASS

Page 6: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

JAVA Java is an innovative / modern programming language that has become the language of choice of programs that need to run on a variety of different computer systems. Java is machine independent language. Java runs on standardized hypothetical computer that is called Java Virtual Machine (JVM) which is emulated inside your computer by a program.

There are two types of programs in java. Small programs that are to be embedded in a web page are called Java Applets. And normal stand alone programs are called Java Applications. You can further subdivide Java Applications into Console Applications, which only support character output to your computer screen and Windowed Java Applications that can create and manage multiple windows. JAVA COMPILER A Java Compiler converts the Java Source Code into a binary program consisting of byte code. Byte codes are machine instructions for the java virtual machine. Java Source Code is always stored in files with the extension .java and Java Byte / Object Code (JBC) is always stored in files with the extension .class JAVA INTERPRETER When you execute a Java program, a program called the Java Interpreter inspects and deciphers the byte code for it, checks it out to ensure that it has not been tampered with and is safe to execute and then executes the action that the byte codes specify within the Java virtual machine.

Java Source Code

Java

Compiler

Java virtual machine

Computer Operating System

Java Byte / Object

Code

Java interpreter

JBC is verified and loaded into the Java virtual Machine

The interpreter handles all communication with the operating system for the real machine

The interpreter executes the program.

XXX.java XXX.class

Page 7: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

JAVA RUN TIME ENVIRONMENT The runtime environment includes the JavaTM Plug-in product which supports running the Java 2 environment inside web browsers. CLASSPATH It is an environment variable. OBJECTS Object is an instance or a member of a class. In OOP you no longer ask how the problem will be divide into functions, but how it will be divided into objects. Thinking in terms of objects, rather than functions. Naming Convention: You can assign any name but for convenient it should be a

Verb with first letter of each word as capital except first word (for example: drawGraph, pushBreak, etc.)

CLASS A set of related objects (functions, behaviors, Methods, Attributes) is called a class. Class has necessary data. Class consist of Data and Operation. Data = fields, variables, properties. Operations = Methods, Behavior.. Naming Convention: You can assign any name but for convenient it should be a

Singular Noun with first letter of each word as capital (for example: Train, Account, Math, etc.)

CONSTRUCTOR When you create an object of a class, a special kind of method called constructor is always invoked. The primary purpose of constructor is to provide you with the means of initializing the instance variables uniquely for the object that is being created. Characteristics: • A constructor never returns a value. • You must not specify a return type not even of type void. • A constructor has always the same name as the class. • A Single class may contain more than one constructor. DEFAULT CONSTRUCTOR If you don’t define any constructor for a class, the compiler will supply a default constructor that has no parameters and does nothing. INHERITANCE The idea of classes leads to the idea of inheritance / birthright. We use the concept of classes as divided into subclasses. Subclass is known as child class and Superclass from which it is derived is known as parent class.

Super / Parent Class

Vehicles

Sub/Child Class Car

Sub/Child Class Bus

Sub/Child Class Truck

No, 112

No, 122

No, 130

No, 150

Page 8: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Each Subclass shares common characteristics with the super class from which it is derived. As here Car, Bus and truck all have wheels and a motor, these are defining characteristics of vehicles. Each subclass also have its own particular characteristics as buses have seats for many peoples and truck have space for hauling heavy loads. POLYMORPHISM The word ‘polymorphism’ generally means the ability to assume several different forms or shapes. In programming terms it means the ability of a single variable of a given type to be used to reference objects of different types, and to automatically call the method that is specific to the type of object the variable references. Note that polymorphism only applies to methods. It does not apply to data member. METHOD OVERLOADING Java allows defining a class more than one function/constructor with the same name but with different number or types of their arguments. This is called method overloading. Overloading is a kind of polymorphism. ABSTRACT CLASS Java permits declaration of classes that define only part of an implementation, leaving the subclasses to provide the details. Abstract class contains abstract methods which have no implementation. INTERFACE Java Interface defines constant & abstract methods. Data fields and methods are CONSTANT and STATIC by default. Interface can be inherited from multiple interfaces. Interface has no implementation. Note: The class that implements Java Interface or extends Java Abstract class must define the definition to all methods defines in Interface or Abstract Class. REUSABILITY Once a class has been written, created and debugged. It can be distributed to other programmers for use in their own programs. This is called reusability. ENCAPSULATION Encapsulation refers to the hiding of items of data and methods within an object. This is achieved by specifying them as private in the definition of the class. The data and implementation is not directly accessible but only through methods. By encapsulation, it is easy to handle changes and easy to reuse. DATA TYPES There are eight fundamental data types which are also known as Primitive data types. INTEGER DATA TYPES

Data Type VALUES Memory Minimum Maximum In Bits In Bytes

byte -128 +127 8 1 Short -32768 +32767 16 2 char 0 65555 16 2 Int -2147483648 +2147483647 32 4 long -9223372036854775808 +9223372036854775807 64 8

Page 9: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

FLOATING DATA TYPES

Data Type VALUES Memory Minimum Maximum In Bits In Bytes

float -3.4 x 1038 +3.4 x 1038 32 4 double -1.7 x 10308 +1.7 x 10308 64 8

BOOLEAN DATA TYPES

Data Type VALUES Memory Minimum Maximum In Bits In Bytes

boolean 0 1 1 ---- VARIABLE A variable is a named piece of memory that you store information in your java program. Each named piece of memory that you define in your program will only be able to store data of one particular type. VARIABLE NAME The name that you choose for a variable that you choose for anything in java is called identifier. An identifier can be any length, but it must start with a latter, an underscore ( _ ) or a dollar sign ($). Java is case sensitive. In java “Animal” not equal to “animal”. OPERATIONS

< Less than - Minus >> Shift left

<= Less than or equal to * Multiplication ~ Complement

> Greater than / Division & And

>= Greater than or equal to % Remainder | OR

= = equal to ++ Increment ^ XOR != Not equal to -- Decrement + Plus << Shift right

LOGICS AND LOOPS

MAKING DECISIONS Making choices will be a fundamental element in all your program. You need to be able to make decisions. In programming term terms this requires the ability to make comparisons between variables, constants and the values of expressions, then executing one group of statements or another depending on the result.

Page 10: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

For comparison following relational operator are used:.

< Less than <= Less than or equal to > Greater than >= Greater than or equal to = = equal to != Not equal to

IF STATEMENT

Syntax 1: if (expression) StatementA; Syntax 2: if (expression){

StatementA1; StatementA2; StatementA3; StatementA4; StatementA5; StatementA7; }

Here, if expression is TRUE then StatementA will execute and if expression is FALSE then StatementA will not execute. IF … ELSE ….STATEMENT

Syntax 1: if (expression){ StatementA; }else { StatementB; } Syntax 2: if (expression){

StatementA1; StatementA2; StatementA3; }else { StatementB1;

StatementB2; StatementB3;

} Here, if expression is TRUE then StatementA will execute and if expression is FALSE then StatementB will execute.

if (expression);

StatementA;

FALSE

TRUE

if (expression)

StatementA; StatementB;

TRUE FALSE

Page 11: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

NESTED IF STATEMENT When an IF statement contain an other IF statement in it, this is called Nested If statement

Example: if (expression){ if (expression){

StatementA; }

}else { if (expression){

StatementB; }

} THE SWITCH STATEMENT The switch statement enables to select from multiple choices based on a set of fixed values for given expression. The expression must produce a result of type char, short or int, but not long, otherwise the statement will not compile.

Syntax: switch (variable Name) { case 1: statementA; break;

case 2: statementB; break; default: statementA; break;

} LOOPS A loop allows you to execute a statement or block of statement repeatedly. FOR LOOP Syntax: for (initial expression; condition; increment or decrement expression) StatementA; Syntax: for (initial expression; condition; increment or decrement expression){ StatementA1; StatementA2; StatementA3; StatementA4; StatementA5; }

Page 12: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

WHILE LOOP Syntax: while (condition expression) StatementA; Syntax: while (condition expression){ StatementA1; StatementA2; StatementA3; StatementA4; StatementA5; } DO WHILE LOOP Syntax: do{ StatementA1; StatementA2; StatementA3; StatementA4; StatementA5; }while (condition expression); NESTED LOOP When a loop statement contain an other loop statement in it, this is called Nested loop. do{

while (condition expression){ StatementA1; StatementA2;

} }while (condition expression); BREAK One can also use the break statement to break out from a loop when you need, when break is executed within a loop the loop ends immediately. ARRAYS An array is a named set of variables of the same data type. Each variable in the array is called an array element. To reference a particular element vin an array you use the array name combined with an integer value of type int, called an index.

int [ ] primes; //declare an integer array variable OR int primes[ ]; //declare an integer array variable int [] primes = new int[10] // define an array of 10 integers.

OR primes = new int[10]; // define an array of 10 integers. char [] vowels={‘a’,’e’,’i’,’o’,’u’};

Page 13: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

STRING String is a set of character. It may be contain characters A to Z, 0 to 9, special symbols (like ! @ # $ % ^ & * ( ) { }) or combination of all these. For strings we do not use = = sign for comparing.

IF(String1= =String2)

Therefore use as if (String1.equals(String2))

DESIGNING OF CLASS

SCOPE OF CLASS

NAME OF CLASS

SCOPE OF DATA / FIELD

TYPE OF DATA / FIELD

NAME FOR DATA / FIELD

SCOPE OF OPERATION / METHODS

TYPE OF OPERATION / METHODS

NAME OF OPERATION / METHODS

PARAMETERS OF OPERATION / METHODS

SCOPE Private: Access only in class for their methods. Public: Any class can access it for their any methods. Protected: Package of class can access it for their methods. JAVA DATA BASE CONNECTIVITY JDBC, by definition, is an interface to relational data sources. Non-relational databases may also be accessible with it also. The JDBC library provides the means of executing SQL statements to access and operate on a RDBMS. The library is implemented in java.sql package. To access any data base through JDBC, a JDBC driver is required for that database which handles Java’s method calls to database API. JDBC provides a driver manager that dynamically maintains all the driver objects that database queries will need.

Page 14: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

SEVEN BASIC STEPS USING JDBC

1. Load the Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

2. Define the connection URL String url = "jdbc:odbc:TestDb";

3. Establish the connection Connection con = DriverManager.getConnection

(url, "myLogin", "myPassword"); 4. Create a Statement object

Statement statement = con.createStatement();

5. Execute query ResultSet resultset = statement.executeQuery(“ SELECT * FROM TABLENMAE“)

6. Process the results While(resultset.next()) { System.out.prinltln(resultset.getString(1)); }

7. Close the connection Con.close();

TYPES OF JDBC DRIVERS There are 4 types of JDBC drivers available. q JDBC-ODBC Bridge Driver, included with JDK connects Java applications with

ODBC drivers. Its class name is sun.jdbc.odbc.JdbcOdbcDriver. q Native API/Partly Java Driver, consists of Java code that accesses data through

native methods, typically to a particular vendor library. q Net Protocol All Java Client are completely implemented in Java, which access to

another middle ware component to access the database. q Native Protocol All Java drivers are completely implemented in Java and directly

communicate to the database.

Page 15: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

VISUAL BASIC Visual Basic is a tool that allows you to develop Windows (Graphic User Interface - GUI) applications. Visual Basic is event-driven, meaning code remains idle until called upon to respond to some event (button pressing, menu selection ...). Visual Basic is governed by an event processor. Nothing happens until an event is detected. Event Procedures - Code related to some object. This is the code that is executed when a certain event occurs. General Procedures - Code not related to objects. This code must be invoked by the application. Modules - Collection of general procedures, variable declarations, and constant definitions used by application

Data Type Suffix Boolean None Integer % Long (Integer) & Single (Floating) ! Double (Floating) # Currency @ Date None Object None String $ Variant None

Variable Declaration There are three ways for a variable to be typed (declared):

• Default • Implicit • Explicit

If Statement ‘ comments Single line if statement

If condition Then Statement ‘ more than one line if statement If condition Then

One or more Visual Basic statements End If If – else statement If condition Then

Page 16: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

One or more Visual Basic statements Else One or more Visual Basic statements End If Select Statement Visual Basic supports Select Case statement that handles such multiple-choice conditions better than If-Else. Select Case Expression Case value

One or more Visual Basic statements Case value

One or more Visual Basic statements [Case value

One or more Visual Basic statements] [Case Else:

One or more Visual Basic statements] End Select Visual Basic data types Data Type

Description

integer Numeric values with no decimal point or fraction. integer values range from –32,768 to 32,767.

long Integer values with a range beyond than that of integer data values. long data values range from –2,147,483,648 to 2,147,483,647. long data values consume more memory storage than integer values, and they are less efficient. The long data type is often called long integer.

single Numeric values that range from –3.402823E+38 to 3.402823E+38. The single data type is often called single-precision.

double single numeric values that range from –1.79769313486232E+308 to 1.79769313486232E+308. The double data type is often called double-precision.

currency Data that holds dollar amounts from –$922,337,203,685,477.5808 to $922,337,203,685,477.5807.

string Data that consists of 0–65,500 characters of alphanumeric data. Alphanumeric means that the data can be both alphabetic and numeric. string data values may also contain special characters such as ^%@.

Page 17: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

variant Used for data stored in controls and for date and time values. Variable - A variable is like a box in memory that holds a data value. To define a variable means to create and name a variable. Dim VarName AS DataType Dim—short for dimension The Val() Function - The Val() function makes sure that Visual Basic treats control values as numbers when you need numbers for expressions. Example – val(textbox.text) The logical operators Operator Usage Description

And If (A > B) And (C < D)

Returns true if both sides of the And are true. Therefore, A must be greater than B and C must be less than D. Otherwise, the expression returns a false result.

Or If (A > B) Or (C < D)

Returns true if either side of the Or is true. Therefore, A must be greater than B or C must be less than D. If both sides of the Or are false, the entire expression returns a false result.

Not If Not(Ans = "Yes")

Produces the opposite true or false result. Therefore, if Ans holds "Yes", the Not turns the true result to false.

The Do While Loop The Do While statement works with relational expressions just as the If statement does Do While (condition) Block of one or more Visual Basic statements Loop The Do Until Loop The Do Until loop works almost exactly like the Do While except that the Do Until loop continues executing the body of the loop until the relational test is true Do Until (condition) Block of one or more Visual Basic statements Loop The Do Loop If a loop begins with a single Do statement, the loop ends with either Loop While or Loop Until. Do

Block of one or more Visual Basic statements

Page 18: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Loop Until (condition)

Or Do

Block of one or more Visual Basic statements Loop While (condition) The For Loop The For loop (sometimes called the For-Next loop) repeats for a specified number of times For CounterVar = StartVal To EndVal [Step IncrementVal]

Block of one or more Visual Basic statements Next CounterVar Array - An array is a list of values Dim ArrayName(subMax) As DataType Argument - An argument is a value that you pass to a function Function - Functions accept one or more arguments and do work with those arguments. The function then returns a single value. Function FunctionName (arguments As DataType)

‘Statements End Function Procedure – Procedures accept one or more arguments and do work with those arguments. The procedure does not return any value. Sub ProcedureName(argument As DataType, Argument As DataType) ‘Statements End Sub

HYPERTEXT MARKUP LANGUAGE (HTML) HTML documents are text files made up of HTML elements. HTML elements are defined using HTML tags that are not case sensitive.

Page 19: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

HTML Tags • HTML tags are used to mark-up HTML elements • HTML tags are surrounded by the two characters < and > • The surrounding characters are called angle brackets • HTML tags normally come in pairs like <b> and </b> • The first tag in a pair is the start tag, the second tag is the end tag • The text between the start and end tags is the element content • HTML tags are not case sensitive, <b> means the same as <B>

<html> <head> <title>Title of page</title> </head> <body> This is my first homepage. <b>This text is bold</b> </body> </html> HTML element This HTML element starts with the start tag <body>, and ends with the end tag </body>. The purpose of the <body> tag is to define the HTML element that contains the body of the HTML document. Tag Attributes Tags can have attributes. Attributes can provide additional information about the HTML elements on your page. This tag defines the body element of your HTML page: <body>. With an added bgcolor attribute, you can tell the browser that the background color of your page should be red, like this: <body bgcolor="red">. This tag defines an HTML table: <table>. With an added border attribute, you can tell the browser that the table should have no borders: <table border="0"> Attributes always come in name/value pairs like this: name="value". Attributes are always added to the start tag of an HTML element. Attribute values should always be enclosed in quotes. Double style quotes are the most common, but single style quotes are also allowed. Headings Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading. <h6> defines the smallest heading. <h1>This is a heading</h1> <h2>This is a heading</h2> <h3>This is a heading</h3> <h4>This is a heading</h4> <h5>This is a heading</h5> <h6>This is a heading</h6>

HTML automatically adds an extra blank line before and after a heading. Paragraphs Paragraphs are defined with the <p> tag. <p>This is a paragraph</p> <p>This is another paragraph</p>

HTML automatically adds an extra blank line before and after a paragraph.

Page 20: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Line Breaks The <br> tag is used when you want to end a line, but don't want to start a new paragraph. The <br> tag forces a line break wherever you place it. <p>This <br> is a para<br>graph with line breaks</p>

The <br> tag is an empty tag. It has no closing tag. Comments in HTML The comment tag is used to insert a comment in the HTML source code. A comment will be ignored by the browser. You can use comments to explain your code, which can help you when you edit the source code at a later date. <!-- This is a comment -->

Note that you need an exclamation point after the opening bracket, but not before the closing bracket. Text Formatting Tags

Tag Description <b> Defines bold text <big> Defines big text <em> Defines emphasized text <i> Defines italic text <small> Defines small text <strong> Defines strong text <sub> Defines subscripted text <sup> Defines superscripted text <ins> Defines inserted text <del> Defines deleted text <s> Deprecated. Use <del> instead <strike> Deprecated. Use <del> instead <u> Deprecated. Use styles instead "Computer Output" Tags

Tag Description <code> Defines computer code text <kbd> Defines keyboard text <samp> Defines sample computer code <tt> Defines teletype text <var> Defines a variable <pre> Defines preformatted text <listing> Deprecated. Use <pre> instead <plaintext> Deprecated. Use <pre> instead

Page 21: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

<xmp> Deprecated. Use <pre> instead Citations, Quotations, and Definition Tags

Tag Description <abbr> Defines an abbreviation <acronym> Defines an acronym <address> Defines an address element <bdo> Defines the text direction <blockquote> Defines a long quotation <q> Defines a short quotation <cite> Defines a citation <dfn> Defines a definition term The Most Common Character Entities

Result Description Entity Name Entity Number non-breaking space &nbsp; &#160; < less than &lt; &#60; > greater than &gt; &#62; & ampersand &amp; &#38; " quotation mark &quot; &#34; ' apostrophe &#39; Some Other Commonly Used Character Entities

Result Description Entity Name Entity Number ¢ cent &cent; &#162; £ pound &pound; &#163; ¥ yen &yen; &#165; § section &sect; &#167; © copyright &copy; &#169; ® registered trademark &reg; &#174; × multiplication &times; &#215; ÷ division &divide; &#247; The Anchor Tag and the Href Attribute HTML uses the <a> (anchor) tag to create a link to another document. An anchor can point to any resource on the Web: an HTML page, an image, a sound file, a movie, etc. The syntax of creating an anchor: <a href="url">Text to be displayed</a>

Page 22: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

The <a> tag is used to create an anchor to link from, the href attribute is used to address the document to link to, and the words between the open and close of the anchor tag will be displayed as a hyperlink. This anchor defines a link to W3Schools: <a href="http://www.w3schools.com/">Visit W3Schools!</a>

The Target Attribute With the target attribute, you can define where the linked document will be opened. The line below will open the document in a new browser window: <a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a>

The Anchor Tag and the Name Attribute The name attribute is used to create a named anchor. When using named anchors we can create links that can jump directly into a specific section on a page, instead of letting the user scroll around to find what he/she is looking for. Below is the syntax of a named anchor: <a name="label">Text to be displayed</a>

The name attribute is used to create a named anchor. The name of the anchor can be any text you care to use. The line below defines a named anchor: <a name="tips">Useful Tips Section</a>

You should notice that a named anchor is not displayed in a special way. To link directly to the "tips" section, add a # sign and the name of the anchor to the end of a URL, like this: <a href="http://www.w3schools.com/html_links.asp#tips"> Jump to the Useful Tips Section</a>

A hyperlink to the Useful Tips Section from WITHIN the file "html_links.asp" will look like this: <a href="#tips">Jump to the Useful Tips Section</a>

Frames With frames, you can display more than one HTML document in the same browser window. Each HTML document is called a frame, and each frame is independent of the others. The disadvantages of using frames are:

• The web developer must keep track of more HTML documents • It is difficult to print the entire page

The Frameset Tag

• The <frameset> tag defines how to divide the window into frames • Each frameset defines a set of rows or columns • The values of the rows/columns indicate the amount of screen area each

row/column will occupy The Frame Tag

Page 23: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

• The <frame> tag defines what HTML document to put into each frame In the example below we have a frameset with two columns. The first column is set to 25% of the width of the browser window. The second column is set to 75% of the width of the browser window. The HTML document "frame_a.htm" is put into the first column, and the HTML document "frame_b.htm" is put into the second column: <frameset cols="25%,75%"> <frame src="frame_a.htm"> <frame src="frame_b.htm"> </frameset>

Frame Tags

Tag Description <frameset> Defines a set of frames <frame> Defines a sub window (a frame) <noframes> Defines a noframe section for browsers that do not handle frames <iframe> Defines an inline sub window (frame) Tables Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td> tag). The letters td stands for "table data," which is the content of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc. <table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table>

How it looks in a browser: row 1, cell 1 row 1, cell 2 row 2, cell 1 row 2, cell 2 Tables and the Border Attribute If you do not specify a border attribute the table will be displayed without any borders. Sometimes this can be useful, but most of the time, you want the borders to show. To display a table with borders, you will have to use the border attribute: <table border="1"> <tr> <td>Row 1, cell 1</td> <td>Row 1, cell 2</td> </tr> </table>

Headings in a Table Headings in a table are defined with the <th> tag.

Page 24: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

<table border="1"> <tr> <th>Heading</th> <th>Another Heading</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table>

How it looks in a browser: Heading Another Heading

row 1, cell 1 row 1, cell 2 row 2, cell 1 row 2, cell 2 Unordered Lists An unordered list is a list of items. The list items are marked with bullets (typically small black circles). An unordered list starts with the <ul> tag. Each list item starts with the <li> tag. <ul> <li>Coffee</li> <li>Milk</li> </ul>

Here is how it looks in a browser: • Coffee • Milk

Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc. Ordered Lists An ordered list is also a list of items. The list items are marked with numbers. An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. <ol> <li>Coffee</li> <li>Milk</li> </ol>

Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc. Forms A form is an area that can contain form elements. Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form. A form is defined with the <form> tag. <form> <input> <input> </form>

Page 25: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Input The most used form tag is the <input> tag. The type of input is specified with the type attribute. The most commonly used input types are explained below. Text Fields Text fields are used when you want the user to type letters, numbers, etc. in a form. <form> First name: <input type="text" name="firstname"> <br> Last name: <input type="text" name="lastname"> </form>

Radio Buttons Radio Buttons are used when you want the user to select one of a limited number of choices. <form> <input type="radio" name="sex" value="male"> Male <br> <input type="radio" name="sex" value="female"> Female </form>

Checkboxes Checkboxes are used when you want the user to select one or more options of a limited number of choices. <form> <input type="checkbox" name="bike"> I have a bike <br> <input type="checkbox" name="car"> I have a car </form>

The Form's Action Attribute and the Submit Button When the user clicks on the "Submit" button, the content of the form is sent to another file. The form's action attribute defines the name of the file to send the content to. The file defined in the action attribute usually does something with the received input. <form name="input" action="html_form_action.asp" method="get"> Username: <input type="text" name="user"> <input type="submit" value="Submit"> </form>

The Image Tag and the Src Attribute In HTML, images are defined with the <img> tag. The <img> tag is empty, which means that it contains attributes only and it has no closing tag. To display an image on a page, you need to use the src attribute. Src stands for "source". The value of the src attribute is the URL of the image you want to display on your page. The syntax of defining an image:

Page 26: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

<img src="url">

The URL points to the location where the image is stored. An image named "boat.gif" located in the directory "images" on "www.w3schools.com" has the URL: http://www.w3schools.com/images/boat.gif. The browser puts the image where the image tag occurs in the document. If you put an image tag between two paragraphs, the browser shows the first paragraph, then the image, and then the second paragraph The Alt Attribute The alt attribute is used to define an "alternate text" for an image. The value of the alt attribute is an author-defined text: <img src="boat.gif" alt="Big Boat">

The "alt" attribute tells the reader what he or she is missing on a page if the browser can't load images. The browser will then display the alternate text instead of the image. It is a good practice to include the "alt" attribute for each image on a page, to improve the display and usefulness of your document for people who have text-only browsers. Backgrounds The <body> tag has two attributes where you can specify backgrounds. The background can be a color or an image. Bgcolor The bgcolor attribute sets the background to a color. The value of this attribute can be a hexadecimal number, an RGB value, or a color name. <body bgcolor="#000000"> <body bgcolor="rgb(0,0,0)"> <body bgcolor="black">

The lines above all set the background color to black. Background The background attribute sets the background to an image. The value of this attribute is the URL of the image you want to use. If the image is smaller than the browser window, the image will repeat itself until it fills the entire browser window. <body background="clouds.gif"> <body background="http://www.w3schools.com/clouds.gif">

The URL can be relative (as in the first line above) or absolute (as in the second line above). Note: If you want to use a background image, you should keep in mind:

• Will the background image increase the loading time too much? Tip: Image files should be maximum 10k

• Will the background image look good with other images on the page? • Will the background image look good with the text colors on the page? • Will the background image look good when it is repeated on the page? • Will the background image take away the focus from the text?

The HTML <font> Tag With HTML code like this, you can specify both the size and the type of the browser output : <p> <font size="2" face="Verdana"> This is a paragraph.

Page 27: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

</font> </p> <p> <font size="3" face="Times"> This is another paragraph. </font> </p>

Font Attributes

Attribute Example Purpose size="number" size="2" Defines the font size size="+number" size="+1" Increases the font size size="-number" size="-1" Decreases the font size face="face-name" face="Times" Defines the font-name color="color-value" color="#eeff00" Defines the font color color="color-name" color="red" Defines the font color The Head Element The head element contains general information, also called meta-information, about a document. Meta means "information about". You can say that meta-data means information about data, or meta-information means information about information. Information Inside the Head Element The elements inside the head element should not be displayed by a browser. According to the HTML standard, only a few tags are legal inside the head section. These are: <base>, <link>, <meta>, <title>, <style>, and <script>. Look at the following illegal construct: <head> <p>This is some text</p> </head>

CSS (Cascading Style Sheets)

• CSS stands for Cascading Style Sheets • Styles define how to display HTML elements • Styles are normally stored in Style Sheets • Styles were added to HTML 4.0 to solve a problem • External Style Sheets can save you a lot of work • External Style Sheets are stored in CSS files • Multiple style definitions will cascade into one

CSS Syntax The CSS syntax is made up of three parts: a selector, a property and a value: selector {property: value}

Page 28: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon and surrounded by curly braces: body {color: black}

If the value is multiple words, put quotes around the value: p {font-family: "sans serif"}

Note: If you wish to specify more than one property, you should separate each property with a semi-colon. The example below shows how to define a center aligned paragraph, with a red text color: p {text-align:center;color:red}

To make the style definitions more readable, you can describe one property on each line, like this: p { text-align: center; color: black; font-family: arial }

CSS Comments You can insert comments in CSS to explain your code, which can help you when you edit the source code at a later date. A comment will be ignored by the browser. A CSS comment begins with "/*", and ends with "*/", like this: /* This is a comment */ p { text-align: center; /* This is another comment */ color: black; font-family: arial }

How to Insert a Style Sheet When a browser reads a style sheet, it will format the document according to it. There are three ways of inserting a style sheet: External Style Sheet An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head>

Internal Style Sheet An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section by using the <style> tag, like this:

Page 29: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

<head> <style type="text/css"> hr {color: sienna} p {margin-left: 20px} body {background-image: url("images/back40.gif")} </style> </head>

The browser will now read the style definitions, and format the document according to it.

ACTIVE SERVER PAGES (ASP) Active Server Pages (ASP) is a Microsoft Technology, used to create dynamic Web pages.ASP can utilize VBScript or Jscript for dynamic content generation. An ASP program is a combination of HTML tags plus scripting elements. Just like any other dynamic content generation technology, when a request to an ASP page is made, all the scripts in the ASP page are processed and then the response is generated to the client. The default scripting language for ASP is VBScript, a subset of Microsoft’s popular Visual Basic programming language. Variables

A variable is a section of memory that is allocated a name by the programmer. These sections of memory can be used to store pieces of information that will be used in the program. They’re simply containers of information that you wish to store.

Before using a variable, one needs to create it. This process is called declaration of a variable, which is done by dim keyword in ASP.

e.g: <% dim abc, a, b %> or <% dim a dim b dim abc %> Above example declares 3 variables abc, a and b.

Looping Controls in ASP

ASP has two types of looping structures: Do While and For….Next.

Page 30: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

For….Next The For…Next structure has 3 parts. The first is a line that describes how many times to repeat the loop. The second part contains a set of lines with action statements that carry out the task to be repeated. Last is a line that indicates the end of the action statements and tells ASP to go back and repeat the action statements again. This loop is commonly used for counting purposes. e.g: <% dim a for a = 1 to 10 response.write a next In this loop, the value of a will start from 1, which will then be sent as response, then as the next is encountered, the loop is repeated again. Do While It’s used to repeat a loop when we are not sure how many loops to perform. So on each loop it performs a test and continues looping as long as specified condition is true. e.g: <% dim c c = 1 do while c <= 10 response.write c c = c +1 loop This loop performs the condition check at the start, then executes the action statements and as soon as loop statement is encountered it again jumps to do while statement and checks the condition. It keeps looping until condition becomes false. Do Loop While You can also place the loop condition at the end of the loop. This will result in that even if the condition is not true, the loop will atleast execute once. e.g: <% dim I I = 1 Do Response.write i Loop while I > 1 Functions and Procedures

ASP allows to write some code once and then run it as many times as needed. These are called Functions or Procedures.

• Procedures carry out an action. For example a Sub would be used to carry out the actions of putting text onto a page. It does not return a value.

• Functions carry out actions and return an answer to your code. A function would be used to calculate a delivery date and return it to main program.

A Procedure start with Sub keyword followed by Procedure name and optional set of parameters, then action statements are followed, followed by End Sub keyword. Similarly Functions start with Function keyword followed by Procedure name and

Page 31: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

optional set of parameters, then action statements are followed, followed by End Function keyword. In order to return a value from a function, the value is assigned to function name. ASP Objects Request Object The request object consists of 5 collections.

q QueryString: When sending a request the client can include name/ value pairs of information within the URL. This collection stores any values provided in the URL. For example, this is sent when Method attribute of a form is set to GET.

q Form: If the client sends a Form request, and sets the Method attribute to POST, then the values of the form are stored in this collection.

q ServerVariables: The web server itself holds a great del of information about the request, contained in HTTP server variables. This information is made available as a collection.

q Cookies: If the client is accepting cookies from the server, it sends information to the server and server stores it in the Cookies collection.

q ClientCertificate: A client certificate is a digital certificate exchanged between client and server to verify the identity of the user attempting to contact the server. If the client sends any security certificates to the server, then they are stored in this collection.

The Response Object

With response object, ASP script can • Send Information back to client using response.write. • Control when to send information back to the client. • Tell the browser to go fetch another page. • Instruct the browser to create a cookie.

ASP buffers the HTML output stream through its Buffer property and Flush, Clear and End methods of Response object. Buffer

It is used to tell the ASP that we will be manually controlling the buffer. It can be turned of by following statement.

<% Response.Buffer = false %> This statement should precede any statement that can generate any HTML, so that

it is not written to the buffer. Flush

This method sends any previously buffered output to the client immediately, but continues processing the script. You can simply call it as follows.

<% Response.Flush %> To use this method, the Buffer property should be set to true. Clear

Page 32: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

This method erases any already buffered HTML. To call this method, simply use following. <% Response.Clear %> Applications, Sessions and Cookies

As the web is evolving from simply serving up pages, to providing access to dynamic information from a wide range of systems, the sites that a user may access begin to look more like a traditional application. In ASP, each virtual directory on server may also be an application as well with all pages in that directory being part of that application. Now with most applications, one would ideally have a profile of each user. In fact there’s a range of questions that you’d probably want to know such as: v How many people are coming to our site? v Who are they? v Where are they coming from? v How long are they staying on our site? v Where do they go as they move through the site? Cookies Collection Both request and response objects have a cookie collection. You can create a cookie using the cookies collection of response of object whereas you can read a cookie previously created by you through request object. Creating cookies ASP provides a one-line instruction method to set the cookies. The syntax for writing cookies in ASP is: <% Response.Cookies(“cookiename”) = value %> You can also add some key/value pairs in cookies also. You can do so in the following way. <% Response.Cookies(“cookiename”)(“key”) = value %> e.g: <% Response.Cookies(“cookie1”)(“Name”) = “Kashif” Response.Cookies(“cookie1”)(“Profession”) = “Teacher” %> A cookie set with basic syntax will persist for as long as the browser is open or until the session expires. To make the cookie persist i.e for the cookie to be written to the client browser’s hard disk, you have to set an expiration date for the cookie. The general syntax for doing this is: <% Response.Cookies(“cookiename”).Expires = “December 10,2002” %> Retrieving cookies Every server that creates a cookie can only read the cookie created by it. ASP can do so using the Cookies collection in request object. You can access cookies in the collection using following syntax. <%= request.cookies(“cookiename”) %> or

Page 33: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

<%= request.cookies(“cookiename”)(“key”) %> Every cookie in the request’s cookies collection has a property of HasKeys, which indicates whether the cookie has any key or not. It returns false if the cookie has no key. The Session ASP allows the developer to track a user from page to page in an application through the use of a session. A user’s session begins when any user without a current session opens any ASP page within an ASP application. The user’s session will continue as they navigate from page to page in the site. There are two ways that a session can be terminated. If the user stops interacting with the application, then session will end after a certain period of time has elapsed. The default value for this time period is 20 minutes, which can be changed by setting the Session.Timeout Property. Another way to terminate session is to put Session.Abondon statement in an ASP page, which terminates the session. The Session object Each client’s unique interaction with the application is called a Session. For ASP to manage these processes, each client has a reference to a unique session object. The session object will allow you to:

Ø Be notified when a user session begins, so that you can take appropriate actions for a new client. This is done by placing the Session_OnStart event handler in Global.asa.

Ø Be notified when a client has ended his session. This can either be caused by a timeout or an explicit method called Abondon. This can be handled by placing the Session_OnEnd event handler in Global.asa.

Ø Store information that can be accessed by the client throughout the session. Like Application object, Session object also contains a contents collection which contains all the variables established for a session and you can manipulate it just like the application object. e.g: <% session(“Name”) = “ali” %> <%= session(“Name”) %> DataBase with ASP OLE-DB is the means by which ASP programs work with databases. The OLE-DB techniques are accessed in ASP through ADO (Active Data Objects). The OLE-DB technology is based on the ODBC and is more generic and efficient w.r.t to ODBC. OLE-DB introduces concept of data providers and data consumers. A data provider basically can be compared to the usual database drivers and data consumers are the applications that use them. The ASP provides access to ADO through a suite of components known as Microsoft Data Access Components (MDAC). These components are based on five main objects.

• Connection – Link between Program and Database • Command – allows to run commands against DB. • Recordset – contains data returned from a specific action on DB. • Record – Allows to handle data kept in semi-structured storage (such as common

files) as though they were db records. • Stream – allows manipulation of data held in web resources.

Page 34: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Connecting to a Data Source The Connection object of ASP features properties and methods you can use to open and close database connections, and to issue queries for updating information. To establish a database connection, you first create an instance of the Connection object. For example, the following script instantiates the Connection object and proceeds to open a connection: <% 'Create a connection object. Set cnn = Server.CreateObject("ADODB.Connection") 'Open a connection using the OLE DB connection string. cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Mydb.mdb" %>

Creating a Connection String Connection string is series of semicolon delimited arguments that define parameters such as the data source provider and the location of the data source. ADO uses the connection string to identify the OLE DB provider and to direct the provider to the data source. The following table lists OLE DB connection strings for several common data sources:

Data Source OLE DB Connection String

Microsoft® Access

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=physical path to .mdb file

Microsoft SQL Server

Provider=SQLOLEDB.1;Data Source=path to database on server

Oracle Provider=MSDAORA.1;Data Source=path to database on server

Microsoft Indexing Service

Provider=MSIDXS.1;Data Source=path to file

The description of different parts of Connection string is as follows.

• Provider – OLE-DB provider(driver) • Driver – Equivalent to OLE-DB provider for ODBC • Initial File Name or Data Source – Physical path of db • User Id – user name if needed • password – password if needed • persist security info – Boolean, should windows remember password for you. • DSN - Used in case you have create a Data Source using Windows ODBC data

sources applet in Control Panel.

Page 35: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

JAVA SERVER PAGES (JSP) Scripting languages The default scripting language for JSP is Java. A scripting language must meet three requirements: 1. It must support the manipulation Java objects. This includes creating objects and, in

the case of JavaBeans, accessing and modifying their properties. 2. It must be able to invoke methods on Java objects. 3. It must include the ability to catch Java exceptions, and specify exception handlers. JavaServer Pages— JSP is a Java based technology that simplifies the process of developing dynamic web sites. With JSP, web designers and developers can quickly incorporate dynamic elements into web pages using embedded Java and a few simple markup tags. These tags provide the HTML designer with a way to access data and business logic stored inside Java objects without having to master the complexities of Java application development.

JSP tags JSP provides four major categories of markup tags. 1. Directives 2. Scripting elements 3. Comments 4. Actions JSP directives Directives are used to convey special processing information about the page to the JSP container. Directives do not directly produce any output that is visible to end-users when the page is requested; instead, they generate side effects that change the way the JSP container processes the page. Page Directive The page directive is the most complicated JSP. <%@ page attribute1="value1" attribute2="value2" attribute3=… %> Like all JSP tag elements, the page directive supports an XML-based syntax, as follows: <jsp:directive.page attribute1="value1" attribute2="value2" attribute3=… /> Include directive The second JSP directive enables page authors to include the contents of one file in another. <%@ include file="localURL" %>

Page 36: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

There are no restrictions on the number of include directives that may appear in a single JSP page. Tag library directive This directive is used to notify the JSP container that a page relies on one or more custom tag libraries. A tag library is a collection of custom tags that can be used to extend the functionality of JSP on a page-by-page basis. <%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %> Comments There are three different ways to insert comments into a JSP page. These three styles of comments themselves divide into two major types: Comments that are transmitted back to the browser as part of the JSP response Those that are only visible in the original JSP source file.

1. Content comments Only one of the three comments styles falls into the first group. These are referred to as content comments, because they use the comment syntax associated with the type of content being generated by the JSP page. <!-- comment --> Example: <!-- This is JSP content comments -->

2. JSP comments JSP comments are independent of the type of content being produced by the page. These comments can only be viewed by examining the original JSP file, and take the following form: <%-- comment --%>

3. Scripting language comments Finally, comments may also be introduced into a JSP page within scriptlets, using the native comment syntax of the scripting language. <% /* comment */%> Actions Actions are the fourth and final major category of JSP tags, and themselves serve three major roles. First, JSP actions allow for the transfer of control between pages. Second, actions support the specification of Java applets in a browser-independent manner. Finally, actions enable JSP pages to interact with JavaBeans component objects residing on the server. Forward

Page 37: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

The <jsp:forward> action is used to permanently transfer control from a JSP page to another location on the local server, which may be a static document, a CGI, a servlet, or another JSP page. Any content generated by the current page is discarded, and processing of the request begins anew at the alternate location. <jsp:forward page="localURL" />

Implicit objects JSP container also exposes a number of its internal objects to the page author. These are referred to as implicit objects, because their availability in a JSP page is automatic. JSP implicit objects and their API’s for HTTP applications Object Class or Interface Description page Javax.servlet.jsp.HttpJspPage Page’s servlet instance config javax.servlet.ServletConfig Servlet configuration data request javax.servlet.http.HttpServletRequest Request data, including

parameters response javax.servlet.http.HttpServletResponse Response data out

javax.servlet.jsp.JspWriter Output stream for page content

session javax.servlet.http.HttpSession User-specific session data application javax.servlet.ServletContext Data shared by all application

pages. pageContext

javax.servlet.jsp.PageContext Context data for page execution

exception java.lang.Throwable Uncaught error or exception The nine implicit objects provided by JSP fall naturally into four major categories:

• Objects related to a JSP page’s servlet • Objects concerned with page input and output • Objects providing information about the context within which a JSP page is being

processed • Objects resulting from errors.

Request object

Page 38: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

For HTTP requests, this object provides access to all of the information associated with a request, including its source, the requested URL, and any headers, cookies, or parameters associated with the request. Example <% String xStr = request.getParameter("num"); try { long x = Long.parseLong(xStr); %> Factorial result: <%= x %>! = <%= fact(x) %> <% } catch (NumberFormatException e) { %> Sorry, the <b>num</b> parameter does not specify an integer value. <% } %> Response object The response object represents the response that will be sent back to the user as a result of processing the JSP page. Example: It is a scriptlet that uses the response object to set various headers for preventing the page from being cached by a browser: <% response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); if (request.getProtocol().equals("HTTP/1.1")) { response.setHeader("Cache-Control", "no-cache"); } %> Out object This implicit object represents the output stream for the page, the contents of which will be sent to the browser as the body of its response. The out object is an instance of the javax.servlet.jsp.JspWriter class. This is an abstract class that extends the standard java.io.Writer class, supplementing it with several of the methods provided by the java.io.PrintWriter class. Example <% int total = out.getBufferSize(); int available = out.getRemaining(); int used = total – available; %> Buffering Status: <%= used %>/<%= total %> = <%= (100.0 * used)/total %>% Session object This object represents an individual user’s current session. All of the requests made by a user that are part of a single series of interactions with the web server are considered to be part of a session. As long as new requests by that user continue to be received by the server, the session persists. If, however, a certain length of time passes without any new requests from the user, the session expires.

Page 39: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

The session object, then, stores information about the session. Information about the session itself is available through the other methods of the HttpSession interface, of which the session object is an instance. Example <% UserLogin userData = new UserLogin(name, password); session.setAttribute("login", userData); %>

JAVASCRIPT

JavaScript

• JavaScript was designed to add interactivity to HTML pages • JavaScript is a scripting language - a scripting language is a lightweight

programming language • A JavaScript is lines of executable computer code • A JavaScript is usually embedded directly in HTML pages • JavaScript is an interpreted language (means that scripts execute without

preliminary compilation) • Everyone can use JavaScript without purchasing a license • JavaScript is supported by all major browsers, like Netscape and Internet Explorer

What can a JavaScript Do? • JavaScript gives HTML designers a programming tool - HTML authors are

normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages

• JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page

• JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

• JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element

Page 40: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

• JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing

JavaScript is Case Sensitive A function named "myfunction" is not the same as "myFunction". Therefore watch your capitalization when you create or call variables, objects and functions. Variables A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value. Rules for Variable names:

• Variable names are case sensitive • They must begin with a letter or the underscore character

Declare a Variable You can create a variable with the var statement: var strname = some value

You can also create a variable without the var statement: strname = some value

Assign a Value to a Variable You assign a value to a variable like this: var strname = "Hege"

Or like this: strname = "Hege"

Arithmetic Operators

Operator Description Example Result + Addition x=2

x+2 4

- Subtraction x=2 5-x

3

* Multiplication x=4 x*5

20

/ Division 15/5 5/2

3 2.5

% Modulus (division remainder) 5%2 10%8 10%2

1 2 0

++ Increment x=5 x++

x=6

-- Decrement x=5 x--

x=4

Assignment Operators

Page 41: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Operator Example Is The Same As = x=y x=y

+= x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y

%= x%=y x=x%y Comparison Operators

Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true

Logical Operators

Operator Description Example

&& and x=6 y=3

(x < 10 && y > 1) returns true

|| or x=6 y=3

(x==5 || y==5) returns false

! not x=6 y=3

!(x==y) returns true Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have three conditional statements:

• if statement - use this statement if you want to execute a set of code when a condition is true

• if...else statement - use this statement if you want to select one of two sets of lines to execute

• switch statement - use this statement if you want to select one of many sets of lines to execute

If and If...else Statement You should use the if statement if you want to execute some code if a condition is true. Syntax

Page 42: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

if (condition) { code to be executed if condition is true } else { code to be executed if condition is false }

Switch Statement You should use the Switch statement if you want to select one of many blocks of code to be executed. Syntax switch (expression) { case label1: code to be executed if expression = label1 break case label2: code to be executed if expression = label2 break default: code to be executed if expression is different from both label1 and label2 }

This is how it works: First we have a single expression (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename=(condition)?value1:value2

Looping Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to do this. In JavaScript we have the following looping statements:

• while - loops through a block of code while a condition is true • do...while - loops through a block of code once, and then repeats the loop while a

condition is true • for - run statements a specified number of times

while The while statement will execute a block of code while a condition is true.. while (condition) { code to be executed }

Page 43: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

do...while The do...while statement will execute a block of code once, and then it will repeat the loop while a condition is true do { code to be executed } while (condition)

for The for statement will execute a block of code a specified number of times for (initialization; condition; increment) { code to be executed }

Comments You can add a comment to your JavaScript code starting the comment with two slashes "//": sum=a + b //calculating the sum

You can also add a comment to the JavaScript code, starting the comment with "/*" and ending it with "*/" sum=a + b /*calculating the sum*/

Using "/*" and "*/" is the only way to create a multi-line comment: /* This is a comment block. It contains several lines*/

Functions Functions allow you to localize a logically related set of statements and variable

declaration for the purposes of modularity, ease in coding, ease in modification and code and data hiding. Most importantly they allow you to break a large problem down into simpler steps. Properly written functions are reusable from program to program, eliminating the coding or debugging altogether. A function in JavaScript can be of two types.

• Ones that don’t return a result (commonly known as subroutines in other programming languages).

• Ones that returns a result. The syntax of a JavaScript function is given below

Syntax Function function_name ( argument_list ) { function_body code for function }

Objects The simplest way to define an object is to think of a logically related set of data

declarations and functions, syntactically bundled together, to do one thing. For example, take a scroll bar in a text editor. The scroll bar object holds the information like its

Page 44: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

current screen co-ordinates, its maximum and minimum value, the increment to use when the user clicks on the arrow, where the thumb is and so on.

Similarly the scroll bar knows how to redraw the thumb if move, resizing the scroll bar if the user reshapes the window etc. So the scroll bar object has data declarations called member data and functions called member functions.

An optional part of an object is called constructor. It is an optional object method having a unique syntax and logical use. Constructors are used to initialize an objects member data. The name of the constructor is the same as the object’s name. The constructor is never directly called. Its automatically called when the object is instantiated. Object instantiation means declaring an object variable. For example

var D = new Date( ) Above statement creates a new date object variable D.

Standard JavaScript Objects There are several JavaScript objects but some of them are

• Date • String • Math

STRUCTURED QUERY LANGUAGE (SQL) CREATE TABLE statement The SQL (Structured Query Language) CREATE TABLE statement creates tables to store data CREATE TABLE [scheme.] table (Column datatype [DEFAULT expression] [, …]); schema is the same as the owner’s name table is the name of the table DEFAULT expression specifies a default value if a value is omitted in the INSERT statement column is the name of the column datatype is the column’s data type & length INSERT Statement To insert the data in the table, use SQL DML statement INSERT INSERT INTO table [(column, [, column...)] VALUES (value [, value…]); table is the name of the table

Page 45: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

column is the name of the column in the table to populate value is the corresponding value for the column SELECT statement The SELECT statement retrieves information from the database SELECT */ {[DISTINCT] column/expression [AS alias],…} FROM table [WHERE condition] [ORDER BY {column, expression}[DESC/ASC]]; * select all columns DISTINCT suppresses duplicates Column/expression selects the named column or the expression alias gives selected columns different headings FROM table specifies the table containing the columns WHERE restricts the query to rows that meet a condition Condition is composed of column names, expressions, Constants & a comparison operator ORDER BY specifies the order in which the retrieved rows are displayed ASC rows in the ascending order (default order) DESC orders the rows in the descending order UPDATE statement The UPDATE statement modifies the existing rows in the table. UPDATE table SET column = value [, column = value, …] [WHERE condition]; table is the name of the table column is the name of the column in the table to populate value is the corresponding value or subquery for the column condition identifies the rows to be updated & is composed of column names, expressions, constants, subqueries & comparision operator DELETE statement The DELETE statement removes the existing rows in the table DELETE [FROM] table [WHERE condition]; table is the name of the table condition identifies the rows to be deleted & is composed of column

Page 46: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

names, expressions, constants, subqueries & comparision operator SQL Functions Functions are a very powerful feature of SQL and can be used to do the following:

• Perform calculations on data • Modify individual data items • Manipulate output for groups of rows • Format dates and numbers for display • Convert column data types

SQL functions sometimes take arguments and always return a value. Types of SQL Functions There are two distinct types of functions:

• Single-row functions • Multiple-row functions

Single-Row Functions These functions operate on single rows only and return one result per row. There are different types of single-row functions. These functions may modify the datatype, can be nested. Single-Row Functions are:

• Character • Number • Date • Conversion

Multiple-Row Functions Functions can manipulate groups of rows to give one result per group of rows. These functions are known as group functions. Group functions operate on sets of groups to give one result per group

PL/SQL PL/SQL (Procedural Language/SQL) is a procedural extension of Oracle-SQL that allows users and designers to develop complex database applications that require the usage of control structures and procedural elements such as procedures, functions, and modules PL/SQL is a block-structured language offered by Oracle to facilitate the use of the Oracle RDBMS. Variables can be declared and used within a PL/SQL block. PL/SQL allows for conditional processing with IF...THEN...ELSE, WHILE...LOOP, FOR...LOOP, EXIT...WHEN, and GOTO functions.

Page 47: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

The primary performance difference between PL/SQL and SQL is the fact that PL/SQL statements are transmitted to Oracle as a block of statements rather than as individual state-ments. The major goals of PL/SQL are to § Increase the expressiveness of SQL, § Process query results in a tuple-oriented way, § Optimize combined SQL statements, § Develop modular database application programs, § Reuse program code, and Reduce the cost for maintaining and changing applications PL/SQL Block Structure DECLARE [OPTIONAL] - variables, cursors, user-defined exceptions BEGIN - SQL statements - PL/SQL statements Exception [OPTIONAL] - actions to perform when errors occur END; Declaring PL/SQL Variables You need to declare all PL/SQL identifiers in the declaration section before referencing them in the PL/SQL block. Syntax identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; identifier is the name of the variable CONSTANT constrains the variable so that its value cannot change; constants must be initialized datatype is a scalar, composite, reference, or LOB datatype NOT NULL constrains the variable so that it must contain a value(NOT NULL

variable must be initialized) expr is any PL/SQL expression that can be literal, another variable or an

expression involving operators and functions The %TYPE Attribute Declare a variable according to:

- A database column definition - Another previously declared variable

Prefix %TYPE with: - The database table and column

Page 48: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

The previously declared variable name Control Structure PL/SQL statements can be controlled by a number of Control Structures such as conditional construct IF statement and LOOP control structures. Three forms of IF statement:

§ IF-THEN-END IF § IF-THEN-ELSE-END IF § IF THEN-ELSEIF-END IF

Syntax IF condition THEN Statements; [ELSEIF condition THEN statements; ] [ELSE statements; ] END IF; LOOPS repeat a statement or sequence of statements multiple times, three loops types are as under:

§ Basic loop (provides repetitive actions without overall conditions) § FOR loop (provides iterative control of actions based on a count) § WHILE loop (provides iterative control of actions based on a condition)

Syntax Basic loop LOOP

Statement1; . . . EXIT [WHEN condition]; END LOOP; Note: EXIT statement terminates loop Syntax FOR loop FOR counter IN [REVERSE] Lower_bound . . upper_bound LOOP Statement1; Statement2; . . . END LOOP; Syntax WHILE loop WHILE condition LOOP Statement1; Statement2; . . . END LOOP;

Page 49: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

LOOPS can be nested means Loop within a Loop. Example DECLARE num NUMBER(3); BEGIN FOR num 1..10 LOOP IF NOT(num=5 OR num=8) THEN ; ELSE INSERT INTO messages values (num); END IF; END LOOP; COMMIT; END Cursors Every SQL statement executed by the Oracle Server has an individual cursor associated with it. There are two types of Cursor 1) Implicit Cursors Declared for all DML and PL/SQL Select statements. 2) Explicit Cursors Declared and named by the programmer. Implicit Cursors The Oracle Server implicitly opens a cursor to process each SQL statement not associated with an

explicitly declared cursor. We cannot use OPEN, FETCH, and CLOSE statements to control the SQL cursor.

Explicit Cursors We can process each row returned by a multiple row Select statement through Explicit Cursors. We have four basic commands to use Explicit Cursors.

1) Declare the cursor by naming it and defining the structure of the query to be performed within it.

2) Open the cursor. The open statement executes the query and binds any variables that are referenced.

3) Fetch Data from Cursor. The fetch statement loads the current row from the cursor into variables. Each fetch causes the cursor to move its pointer to the next row in the active set. If rows are found, the fetch loads the current row into variables; otherwise, it closes the cursor.

4) Close the Cursor. The close statement releases the active set of rows. It is now possible to reopen the cursor to establish a fresh active set.

Page 50: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Declaring Cursor Syntax CURSOR cursor_name IS Select _ statement; Example DECLARE

CURSOR emp_cursor IS SELECT empno, ename from emp; begin……

Opening Cursor Syntax

OPEN cursor_name; Fetching Data from Cursor Syntax FETCH cursor_name INTO [variable1, variable2,----]; Example FETCH emp_cursor INTO v_empno, v_ename; Closing Cursor Syntax CLOSE cursor_name; Handling Exceptions Run-time errors arise from design faults, coding mistakes, hardware failures, and many other sources. In PL/SQL, a warning or error condition is called an exception. Exceptions can be internally defined (by the run-time system) or user defined. Internally defined exceptions include division by zero and out of memory. Some common internal exceptions have predefined names, such as ZERO_DIVIDE and STORAGE_ERROR. The others can be given names. An exception is an identifier in PL/SQL, raised during the execution of a block that terminates its main body of actions. A block always terminates when PL/SQL raises an exception but you specify an exception handler to perform final actions. There are two methods for raising exceptions

1) An Oracle error occurs and the associated exception is raised automatically. 2) You raise an exception explicitly by issuing the RAISE statement within

the block. Exception Types

1) Predefined Oracle Server (implicitly raised)

Page 51: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

2) Non-predefined Oracle Server (implicitly raised) 3) User_defined (explicitly raised)

Predefined Exceptions Trap a predefined Oracle Server error by referencing its standard name within the corresponding exception-handling routine. Syntax

BEGIN SELECT …….COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN Statement1; Statement2; WHEN TOO_MANY_ROWS THEN Statement1; WHEN OTHERS THEN Statement1; End;

Non-Predefined Exceptions You can trap a non-predefined Oracle Server error by declaring it first, or by using the OTHER

handler. The declared exception is raised implicitly. The progma EXCEPTION_INIT tells the compiler to associate an exception name with an Oracle Error number.

Example DECLARE e_emps_remaining EXCEPTION; PROGMA EXCEPTION_INIT(e_emps_remaining, -2292); v_deptno dept.deptno%type := &p_deptno; BEGIN DELETE FROM dept WHERE deptno = v_deptno; COMMIT; EXCEPTION WHEN e_emps_remaining THEN

DBMS_OUTPUT.PUT_LINE (‘cannot remove dept’ || TO_CHAR(v_deptno) || ‘.Employees exist.’);

END;

User-defined Exceptions PL/SQL lets u define your own exceptions. User defined exceptions must be.

Ø Declared in the declare section of a PL/SQL block. Ø Raised explicitly with RAISE statements.

Example DECLARE e_invalid_product EXCEPTION; BEGIN

Page 52: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

UPDATE product SET descrip=’&product_description’ WHERE prodid= & product_number; IF SQL%NOTFOUND THEN RAISE e_invalid_product; END IF; COMMIT; EXCEPTION WHEN e_invalid_product THEN

DBMS_OUTPUT.PUT_LINE (‘Invalid product number.’); END;

DATABASE CONCEPTS & ORACLE 9i

In 1977, Larry Ellison, Bob Miner, and Ed Oates formed a company called Relational Software Incorporated (RSI). This company built an RDBMS called Oracle. Oracle introduced Oracle9i, which added object extensions as well as a host of new features and administrative tools. Ad-Hoc Query - This use of the Latin term means an impromptu, simple query Buffer - This term refers to an amount of memory used to store data. A buffer stores data that is about to be used or that has just been used Cache - A cache is a storage area used to provide fast access to data. In hardware terms, the cache is a small (relative to main RAM) amount of memory that is much faster than main memory Checkpoint - A checkpoint is an operation that forces all changed, in-memory data blocks to be written out to disk Data Dictionary - The data dictionary is a set of tables Oracle uses to maintain information about the database. The data dictionary contains information about tables, indexes, clusters, and so on. DBA (Database Administrator) - The DBA is the person responsible for the operation, configuration, and performance of the database DBMS - The Database Management System is the software and collection of tools that manages the database. Oracle software is the DBMS RDBMS - A Relational Database Management System is a DBMS that is relational in nature. This means that the internal workings access data in a relational manner. Oracle is an RDBMS

Page 53: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Dirty Buffer - A dirty buffer is a buffer that has been modified DDL (Data Definition Language) Commands These commands are used in the creation and modification of schema objects. These commands provide the ability to create, alter, and drop objects; grant and revoke privileges and roles; establish auditing options; and add comments to the data dictionary DML (Data Manipulation Language) Commands These commands allow you to query and modify data within existing schema objects. Unlike the DDL commands, a commit is not implicit. DML statements consist of DELETE, INSERT, SELECT, and UPDATE statements; EXPLAIN PLAN statements; and LOCK TABLE statements. Function / Procedure A function is a set of SQL or PL/SQL statements used together to execute a particular function. Procedures and functions are identical except that functions always return a value (procedures do not). Query - A query is a read-only transaction against a database. A query is generated using the SELECT statement Schema - A schema is a collection of objects associated with the database Schema Objects - Schema objects are abstractions or logical structures that refer to database objects or structures. Schema objects consist of such things as clusters, indexes, packages, sequences, stored procedures, synonyms, tables, views, and so on System Global Area (SGA) The SGA is a shared-memory region that Oracle uses to store data and control information for one Oracle instance Transaction - A transaction is a logical unit of work consisting of one or more SQL statements, ending in a commit or a rollback Trigger - A trigger is a mechanism that allows you to write procedures that are automatically executed whenever an INSERT, UPDATE, or DELETE statement is executed on a table or view Virtual Memory - This term refers to the memory that can be used for programs in the operating system DSS - The Decision Support System (DSS) is used to assist with the decision-making process. The DSS system is used to help make decisions by providing good data OLTP - The Online Transaction Processing (OLTP) systems have online users that access the system. These systems are typically used for order-entry purposes, such as for retail sales, credit-card validation, ATM transactions, and so on Data Warehouse A data warehouse is typically considered to be a large-scale system that consists of both DSS and OLTP components. These systems are typically hundreds of gigabytes in size and support many users. Data Mart A data mart, which is a smaller-scale version of a data warehouse, serves many of the same functions as a data warehouse OLAP - The term OLAP (Online Analytical Processing) is usually used in relation with multidimensional data. OLAP users might be financial analysts or marketing personnel looking at global data. Datafiles--Datafiles store the information contained in the database

Page 54: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Redo log files--Redo log files hold information used for recovery in the event of a system failure Control files--Control files contain information used to start an instance, such as the location of datafiles and redo log files; Oracle needs this information to start the database instance Tablespace - A tablespace is used to logically group data together Table--A table, which consists of a tablename and rows and columns of data, is the basic logical storage unit in the Oracle database Cluster--A cluster is a set of tables physically stored together as one table that shares a common column Index--An index is a structure created to help retrieve data more quickly and efficiently View--A view is a window into one or more tables. A view does not store any data; it presents table data. A view can be queried, updated, and deleted as a table without restriction. Stored procedure--A stored procedure is a predefined SQL query that is stored in the data dictionary. Stored procedures are designed to allow more efficient queries Database trigger--A database trigger is a procedure that is run automatically when an event occurs Sequence--The Oracle sequence generator is used to automatically generate a unique sequence of numbers in cache Data blocks--A block is the smallest unit of storage in an Oracle database. The database block contains header information concerning the block itself as well as the data Extents--Extents consist of data blocks Segments--A segment is a set of extents used to store a particular type of data An Oracle database can use four types of segments:

• Data segment--Stores user data within the database. • Index segment--Stores indexes. • Rollback segment--Stores rollback information used when data must be rolled

back. • Temporary segment--Created when a SQL statement needs a temporary work

area; these segments are destroyed when the SQL statement is finished. These segments are used during various database operations, such as sorts.

The Oracle Instance The Oracle instance consists of the Oracle processes and shared memory necessary to access information in the database. The instance is made up of the user processes, the Oracle background processes, and the shared memory used by these processes The Program Global Area (PGA) The PGA is a memory area that contains data and control information for the Oracle server processes User Processes - User, or client, processes are the user's connections to the RDBMS system. The user process manipulates the user's input and communicates with the Oracle server process through the Oracle program interface

Page 55: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Oracle Processes - Oracle processes perform functions for users. Oracle processes can be split into two groups: server processes (which perform functions for the invoking process) and background processes (which perform functions on behalf of the entire RDBMS). Server Processes (Shadow Processes) Server processes, also known as shadow processes, communicate with the user and interact with Oracle to carry out the user's requests. Background Processes Background processes are used to perform various tasks within the RDBMS system. These tasks vary from communicating with other Oracle instances and performing system maintenance and cleanup to writing dirty blocks to disk Following are brief descriptions of the nine Oracle background processes:

• DBWR (Database Writer)--DBWR is responsible for writing dirty data blocks from the database block buffers to disk. When a transaction changes data in a data block, that data block need not be immediately written to disk

• LGWR (Log Writer)--The LGWR process is responsible for writing data from the log buffer to the redo log.

• CKPT (Checkpoint)--The CKPT process is responsible for signaling the DBWR process to perform a checkpoint and to update all the datafiles and control files for the database to indicate the most recent checkpoint. A checkpoint is an event in which all modified database buffers are written to the datafiles by the DBWR.

• PMON (Process Monitor)--PMON is responsible for keeping track of database processes and cleaning up if a process prematurely dies (PMON cleans up the cache and frees resources that might still be allocated). PMON is also responsible for restarting any dispatcher processes that might have failed.

• SMON (System Monitor)--SMON performs instance recovery at instance startup. This includes cleaning temporary segments and recovering transactions that have died because of a system crash. The SMON also defragments the database by coalescing free extents within the database.

• RECO (Recovery)--RECO is used to clean transactions that were pending in a distributed database. RECO is responsible for committing or rolling back the local portion of the disputed transactions

• ARCH (Archiver)--ARCH is responsible for copying the online redo log files to archival storage when they become full. ARCH is active only when the RDBMS is operated in ARCHIVELOG mode. When a system is not operated in ARCHIVELOG mode, it might not be possible to recover after a system failure

• LCKn (Parallel Server Lock)--Up to 10 LCK processes are used for interinstance locking when the Oracle Parallel Server option is used.

• Dnnn (Dispatcher)--When the Multithreaded Server option is used, at least one Dispatcher process is used for every communications protocol in use. The Dispatcher process is responsible for routing requests from the user processes to available shared server processes and back.

Parallel Query - The Oracle parallel query allows a single query to be divided into components and run in parallel.

Page 56: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

The Oracle Web server--The Oracle Web server is designed to provide front-end services to allow World Wide Web access to an Oracle database Developer/2000--This set of tools allows you to create an application and roll it out in Windows, Macintosh, Motif, and character mode. Developer/2000 incorporates graphics and images as well as support for multimedia objects such as video and sound in a variety of standard formats. SQL*Plus - SQL*Plus is the ad-hoc user interface tool for the Oracle RDBMS. With SQL*Plus, you can connect into the RDBMS and run SQL commands and PL/SQL programs. This is the primary nonapplication interface into the Oracle RDBMS. SQL*Net - A SQL*Net is Oracle's communication protocol. SQL*Net uses various network communication protocols such as TCP/IP, DECNet, and SPX/IPX, and provides a common programming layer for the Oracle developer. Oracle Enterprise Manager - A The Oracle Enterprise Manager is the new graphical administration tool designed to help the DBA manage one or more Oracle systems. The DBA Account - To accomplish these tasks, the DBA must be given special privileges. These privileges allow the DBA to run commands that other Oracle users are not allowed to perform. A The primary duty of the DBA is to protect the database and provide continuous (if required) access to that data for the user community SYS account The SYS account is automatically created whenever a database is created. This account is used primarily to administer the data dictionary. This account is granted the DBA role, as well as CONNECT and RESOURCE roles SYSTEM account The SYSTEM account is also automatically created whenever a database is created. This account is used primarily to create tables and views important to the operation of the RDBMS. This account has been granted the DBA role.

log-file group - A log-file group is a set of log files that is used to store system redo information. By having a group of log files, Oracle will automatically mirror redo information to the log files in the groups.

Dedicated server process - A dedicated server process has a one-to-one correlation between the user process and the server process. Each user process gets one server process.

Shared server process - The shared server process handles more than one user process. The dispatcher queues the job and the shared server process executes it.

Unique Index - unique index is an index value that has the additional constraint that the set of indexed columns defines a unique row

Page 57: Naeem Ahmed MahotoNaeem Ahmed Mahoto Email: naeemmahoto@gmail.com General Notes Java JavaScript Visual Basic ASP and JSP Database Concepts GENERAL CONCEPTS OLE (Object Linking and

Nonunique Index - nonunique index does not impose the constraint that the index value be unique. Such an index can be quite useful when quick access is desired on a nonunique value

The PL/SQL Language PL/SQL is a block-structured language offered by Oracle to facilitate the use of the Oracle RDBMS. Variables can be declared and used within a PL/SQL block. PL/SQL allows for conditional processing with IF...THEN...ELSE, WHILE...LOOP, FOR...LOOP, EXIT...WHEN, and GOTO functions. The primary performance difference between PL/SQL and SQL is the fact that PL/SQL statements are transmitted to Oracle as a block of statements rather than as individual state-ments.

foreign key--An attribute requiring that a value must exist in another object, if not NULL, and be its primary key

primary key--Attributes used to uniquely identify a row in a table.

join--A query that selects data from more than one table. The data selected from the different tables is determined by conditions specified within the FROM clause of the statement. These conditions are called join conditions.

join condition--The specification within the WHERE clause of a query join that specifies the manner in which the rows in the different tables are paired.

nonequijoin--A join statement that does not use an equality operation. The converse of this is the equijoin operation

equijoin--A join statement that uses an equivalency operation. The converse of this is the nonequijoin operation.

outer join--A join operation that uses the outer join operator (+) in one of the join statements. The output of an outer join is the rows that satisfy the join condition and those rows in the first table for which no rows in the second table satisfy the join condition.

self join--A join in which a table is joined with itself

shared pool--The area in the SGA that contains the data dictionary cache and shared parsed SQL statements