Java/Servlet/JSP/JDBC

107
INTRODUCTION TO JAVA SERVLET JSP(JAVA SERVER PAGE) DATA BASE CONNECTION

description

Introduction To Java / Servlet /Jsp(java Server Page) /Data Base Connection

Transcript of Java/Servlet/JSP/JDBC

Page 1: Java/Servlet/JSP/JDBC

INTRODUCTION TO JAVASERVLET

JSP(JAVA SERVER PAGE) DATA BASE CONNECTION

Page 2: Java/Servlet/JSP/JDBC

INTRODUCTION TO JAVA

Page 3: Java/Servlet/JSP/JDBC

HISTORY Java is a programming language created by

James Gosling from Sun Microsystems (Sun) in 1991.

Java is a high-level programming language. Its a platform independent.

Java language is called as an Object-Oriented Programming language

Page 4: Java/Servlet/JSP/JDBC

WHY JAVA

It’s the current “hot” language It’s almost entirely object-oriented It’s more platform independent It’s more secure

Page 5: Java/Servlet/JSP/JDBC

WHERE IT IS USED?Desktop Applications such as acrobat reader,

media player, antivirus etc.Web ApplicationsEnterprise Applications such as banking

applications. Mobile Embedded System Smart Card Robotics Games etc.

Page 6: Java/Servlet/JSP/JDBC

JAVA FEATURES

Compiled and Interpreted Platform Independent and portable Object-oriented Robust and secure Distributed Familiar, simple and small Multithreaded and Interactive

Page 7: Java/Servlet/JSP/JDBC

PLATFORM INDEPENDENT

Page 8: Java/Servlet/JSP/JDBC

OBJECT-ORIENTED PROGRAMMING

Page 9: Java/Servlet/JSP/JDBC

DIFFERENT PROGRAMMING PARADIGMS

Functional/procedural programming:• program is a list of instructions to the

computer

Object-oriented programming• program is composed of a collection objects

that communicate with each other

Page 10: Java/Servlet/JSP/JDBC

MAIN CONCEPTS

1. Objects.

2. Classes.

3. Data Abstraction.

4. Data Encapsulation.

5. Inheritance.

6. Polymorphism.

Page 11: Java/Servlet/JSP/JDBC

JVM

JVM stands for Java Virtual Machine

The Java runtime employs a garbage collection to reclaim the memory occupied by on object.

Page 12: Java/Servlet/JSP/JDBC

OS/Hardware

machine codeC source code

myprog.cgcc

myprog.exe

Platform Dependent

JVM

bytecodeJava source code

myprog.javajavac

myprog.class

OS/Hardware

Platform Independent

Page 13: Java/Servlet/JSP/JDBC

What is JVM? A specification where working of Java Virtual

Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.

An implementation Its implementation is known as JRE (Java Runtime Environment).

Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.

Page 14: Java/Servlet/JSP/JDBC

What it does?The JVM performs following operation:

Loads code Verifies code Executes code Provides runtime environment

JVM provides definitions for the: Memory area Class file format Register set Garbage-collected heap Fatal error reporting etc.

Page 15: Java/Servlet/JSP/JDBC

Internal Architecture of JVM

Page 16: Java/Servlet/JSP/JDBC

JAVA KEYWORDS

Abstract,const,finally,int,public,this,boolean,continue,float

interface,return,throw,break,default,for,long,short,throws

byte,do,goto,native,static,transient,case,double,if,new,strictfp

try,catch,else,implements,package,super,void,char,extends

import,private,switch,volatile,class,final,instanceof,protected

synchronized,while

Page 17: Java/Servlet/JSP/JDBC

PRIMITIVE TYPES int 4 bytes short 2 bytes long 8 bytes Byte 1 byte Float 4 bytes double 8 bytes char Unicode encoding (2 bytes) boolean {true, false}

Behaviors is exactly as in C++

Note:Primitive typealways beginwith lower-case

Page 18: Java/Servlet/JSP/JDBC

CONTROL STATEMENTSJava control statements cause the flow of

execution to advance and branch based on the changes to the state of the program.

Control statements are divided into three groups: 1) selection statements allow the program to choose different parts of the execution based on the outcome of an expression 2) iteration statements enable program execution to repeat one or more statements 3) jump statements enable your program to execute in a non-linear fashion

Page 19: Java/Servlet/JSP/JDBC

FLOW CONTROL

if/else

do/while

for

switch

If(x==4) { // act1} else { // act2}

int i=5;do { // act1 i--;} while(i!=0);

int j;for(int i=0;i<=9;i++) { j+=i;}

char c=IN.getChar();switch(c) { case ‘a’: case ‘b’: // act1 break; default: // act2}

Page 20: Java/Servlet/JSP/JDBC

ACCESS CONTROL public member (function/data) • Can be called/modified from outside.

protected• Can be called/modified from derived classes

private• Can be called/modified only from the current

class default ( if no access modifier stated )• Usually referred to as “Friendly”. • Can be called/modified/instantiated from the

same package.

Page 21: Java/Servlet/JSP/JDBC

ARRAYS

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Arrays are:1) declared2) Created

Page 22: Java/Servlet/JSP/JDBC

EXAMPLE

Declaration:

double[] myList; Creating Arrays:

double[] myList = new double[10];

↓[Array

Index]

Page 23: Java/Servlet/JSP/JDBC

THREAD

Thread is a lightweight process that executes some task.

Java is a multithreaded programming language.Multithreading refers to two or more tasks

executing concurrently within a single program.Every thread in Java is created and controlled by

the java.lang.Thread class.

Page 24: Java/Servlet/JSP/JDBC

BENEFITS OF THREADS

Threads are lightweight compared to processes, it takes less time and resource to create a thread.

less expensive.Thread intercommunication is relatively easy

than process communication.

Page 25: Java/Servlet/JSP/JDBC

LIFE CYCLE OF A THREAD:

Page 26: Java/Servlet/JSP/JDBC

EXCEPTIONS HANDLING

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:

• A user has entered invalid data.• A file that needs to be opened

cannot be found.• A network connection has been lost

in the middle of communications or the JVM has run out of memory.

Page 27: Java/Servlet/JSP/JDBC

EXCEPTIONS HANDLING (CONT)

Three categories of exceptions:• Checked exceptions• Runtime exceptions• Errors

Exception Handling Keywords• throw• throws• try-catch• finally

Page 28: Java/Servlet/JSP/JDBC

Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.

Page 29: Java/Servlet/JSP/JDBC

ABSTRACT WINDOWING TOOLKIT (AWT):

Page 30: Java/Servlet/JSP/JDBC

Abstract Windowing Toolkit (AWT) is used for GUI programming in java.

Computer users today expect to interact with their computers using a graphical user interface (GUI).

There are two basic types of GUI program in Java:

• stand-alone applications • applets.

Page 31: Java/Servlet/JSP/JDBC

AWT CONTAINER HIERARCHY:

Page 32: Java/Servlet/JSP/JDBC

Commonly used Methods of Component class:

1)public void add(Component c)

2)public void setSize(int width , int height)

3)public void setLayout(LayoutManager m)

4)public void setVisible(boolean)

Page 33: Java/Servlet/JSP/JDBC

Example:

import java.awt.*;  

class First extends Frame{  

First(){  

Button b=new Button("click me");  

b.setBounds(30,100,80,30);// setting button position  

add(b);//adding button into frame  

setSize(300,300);//frame size 300 width and 300 height  

setLayout(null);//no layout now bydefault BorderLayout 

 setVisible(true);//now frame willbe visible, bydefault not visible  

}  

public static void main(String args[]){  

First f=new First();  

}  

}  

Page 34: Java/Servlet/JSP/JDBC

Output:

Page 35: Java/Servlet/JSP/JDBC

SWING COMPONENTS Swing is a collection of libraries that contains

primitive widgets or controls used for designing Graphical User Interfaces (GUIs).

Commonly used classes in javax.swing package:• JButton, JTextBox, JTextArea, JPanel,

JFrame, JMenu, JSlider, JLabel, JIcon, …• There are many, many such classes to do

anything imaginable with GUIs

Page 36: Java/Servlet/JSP/JDBC

Each component is a Java class with a fairly extensive inheritency hierarchy:

Page 37: Java/Servlet/JSP/JDBC

Using Swing Components Very simple, just create object from appropriate class –

examples:• JButton but = new JButton();• JTextField text = new JTextField();• JTextArea text = new JTextArea();• JLabel lab = new JLabel();

Adding componentsOnce a component is created, it can be added to a container by calling the container’s add method:

• Container cp = getContentPane();

• cp.add(new JButton(“cancel”));

• cp.add(new JButton(“go”));

Page 38: Java/Servlet/JSP/JDBC

APPLETApplet is a special type of program that is embedded in

the webpage to generate the dynamic content. It runs inside the browser and works at client side.

Advantage of Applet It works at client side so less response time.Secured It can be executed by browsers running

under many plateforms, including Linux, Windows, Mac Os etc.

Drawback of AppletPlugin is required at client browser to

execute applet.

Page 39: Java/Servlet/JSP/JDBC

HIERARCHY OF APPLET

Page 40: Java/Servlet/JSP/JDBC

LIFECYCLE OF AN APPLET: Applet is initialized. Applet is started. Applet is painted. Applet is stopped. Applet is destroyed.

public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.

Page 41: Java/Servlet/JSP/JDBC

SIMPLE EXAMPLE OF APPLET

//First.java  

import java.applet.Applet;  

import java.awt.Graphics;  

public class First extends Applet{  

 public void paint(Graphics g){  

g.drawString("welcome to applet",150,150);  

}  

 }  

/* 

<applet code="First.class" width="300" height="300"> 

</applet> 

*/  

Page 42: Java/Servlet/JSP/JDBC

SERVLET INTRODUCTION

Page 43: Java/Servlet/JSP/JDBC

SERVLET Servlet technology is used to create web application.Servlet technology is robust and scalable as it uses the java language. Before Servlet, CGI (Common Gateway Interface) scripting language was used as a server-side programming language. But there were many disadvantages of this technology.

Disadvantages of CGI If number of clients increases, it takes more time for

sending response. For each request, it starts a process and Web server is

limited to start processes. It uses platform dependent language e.g. C, C++, perl.

Page 44: Java/Servlet/JSP/JDBC

CGI(Commmon Gateway Interface)

Page 45: Java/Servlet/JSP/JDBC

Advantage of Servlet better performance: because it creates a thread for

each request not process. Portability: because it uses java language. Robust: Servlets are managed by JVM so no need

to worry about momory leak, garbage collection etc. Secure: because it uses java language..

Page 46: Java/Servlet/JSP/JDBC

Life Cycle of a Servlet (Servlet Life Cycle)The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

Servlet class is loaded. Servlet instance is created. init method is invoked. service method is invoked. destroy method is invoked.

Page 47: Java/Servlet/JSP/JDBC

Servlet APIThe javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

Interfaces in javax.servlet package

There are many interfaces in javax.servlet package. They are as follows: Servlet ServletRequest ServletResponse RequestDispatcher ServletConfig ServletContext Filter FilterConfig FilterChain

Page 48: Java/Servlet/JSP/JDBC

ServletRequest InterfaceAn object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header informations, attributes etc.

Methods of ServletRequest interface: public String getParameter(String name) public String[] getParameterValues(String name) java.util.Enumeration getParameterNames() public int getContentLength() public String getCharacterEncoding() public String getContentType() public ServletInputStream getInputStream() throws

IOException

Page 49: Java/Servlet/JSP/JDBC

RequestDispatcher in ServletThe RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.

Methods of RequestDispatcher interface public void forward(ServletRequest request,ServletResponse

response)throws ServletException,java.io.IOException public void include(ServletRequest request,ServletResponse

response)throws ServletException,java.io.IOException

Page 50: Java/Servlet/JSP/JDBC

Example of RequestDispatcher interface

Page 51: Java/Servlet/JSP/JDBC

Session simply means a particular interval of time. Session Tracking is a way to maintain state (data) of an

user. It is also known as session management in servlet. Http protocol is a stateless so we need to maintain state

using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.

SESSION TRACKING IN SERVLETS

Page 52: Java/Servlet/JSP/JDBC

Session Tracking TechniquesThere are four techniques used in Session tracking:

Cookies Hidden Form Field URL Rewriting HttpSession

Page 53: Java/Servlet/JSP/JDBC

Cookies in ServletA cookie is a small piece of information that is persisted between the multiple client requests.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

Page 54: Java/Servlet/JSP/JDBC

Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side.

Disadvantage of Cookies It will not work if cookie is disabled from the

browser. Only textual information can be set in Cookie

object.

Page 55: Java/Servlet/JSP/JDBC

Hidden Form FieldIn case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.

<input type="hidden" name="uname" value="Vimal Jaiswal">  

Advantage of Hidden Form Field It will always work whether cookie is

disabled or not.Disadvantage of Hidden Form Field:

It is maintained at server side. Extra form submission is required on each pages.

Only textual information can be used.

Page 56: Java/Servlet/JSP/JDBC

Example of using Hidden Form Field

Page 57: Java/Servlet/JSP/JDBC

URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter

name/value pairs using the following format:url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&).

Page 58: Java/Servlet/JSP/JDBC

Advantage of URL Rewriting

It will always work whether cookie is disabled or not (browser independent).

Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

It will work only with links. It can send Only textual

information.

Page 59: Java/Servlet/JSP/JDBC

Example of using URL Rewriting

Page 60: Java/Servlet/JSP/JDBC

HttpSession interface

In such case, container creates a session id for each user. The container uses this id to identify the particular user. An object of HttpSession can be used to perform two tasks:

bind objects view and manipulate information about a session,

such as the session identifier, creation time, and last accessed time.

The HttpServletRequest interface provides two methods to get the object of HttpSession:

public HttpSession getSession() public HttpSession getSession(boolean create)

Page 61: Java/Servlet/JSP/JDBC
Page 62: Java/Servlet/JSP/JDBC

Event and Listener in Servlet

Events are basically occurrence of something. Changing the state of an object is known as an event.

Event classes

The event classes are as follows: ServletRequestEvent ServletContextEvent ServletRequestAttributeEvent ServletContextAttributeEvent HttpSessionEvent HttpSessionBindingEvent

Page 63: Java/Servlet/JSP/JDBC

JSP(JAVA SERVER PAGE)

Page 64: Java/Servlet/JSP/JDBC

JSP technology is used to create web application just like Servlet technology.

A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than servlet because we

can separate designing and development. It provides some additional features such as Expression

Language, Custom Tag etc.

Advantage of JSP over Servlet Extension to Servlet Easy to maintain Fast Development: No need to recompile and

redeploy Less code than Servlet

Page 65: Java/Servlet/JSP/JDBC

Life cycle of a JSP Page

Page 66: Java/Servlet/JSP/JDBC

JSP Scriptlet tag (Scripting elements) In JSP, java code can be written inside the jsp page using the

scriptlet tag.

Scripting elementsThe scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements:

scriptlet tag expression tag declaration tag

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

<%  java source code %>  

Page 67: Java/Servlet/JSP/JDBC

JSP expression tagThe code placed within expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method.

Syntax of JSP expression tag

<%=  statement %> 

JSP Declaration TagThe JSP declaration tag is used to declare fields and methods.The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet.

Syntax of JSP declaration tag

<%!  field or method declaration %>  

Page 68: Java/Servlet/JSP/JDBC

JSP Implicit ObjectsThese objects are created by the web container that are available to all the jsp pages. A list of the 9 implicit objects is given below:

out request response config application session pageContext page exception

Page 69: Java/Servlet/JSP/JDBC

Example of implicit object

Out: <%out.print("Today"+java.util.Calendar.getInstance().getTime()); %>

Request:<%   String name=request.getParameter(“xxx");  %> 

Response:<% response.sendRedirect("http://www.google.com"); %>  Session:<% session.setAttribute("user", xxx);  %>

<% String name=(String)session.getAttribute("user"); );  %>  Exception:<%@ page errorPage="error.jsp" %>  <%@ page isErrorPage="true" %> 

Page 70: Java/Servlet/JSP/JDBC

JSP directivesThe jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet. There are three types of directives:

page directive include directive taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>  

Attributes of JSP page directive import contentType isELIgnored Session errorPage isErrorPage

Page 71: Java/Servlet/JSP/JDBC

Jsp Include DirectiveThe include directive is used to include the contents of any resource it may be jsp file, html file or text file.

Advantage of Include directive Code Reusability

Syntax of include directive

<%@ include file="resourceName" %>  

JSP Taglib directiveThe JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags.

Syntax JSP Taglib directive

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>  

Page 72: Java/Servlet/JSP/JDBC

Exception Handling in JSPThe exception is normally an object that is thrown at runtime. Exception Handling is the process to handle the runtime errors. There may occur exception any time in your web application. So handling exceptions is a safer side for the web developer. In JSP, there are two ways to perform exception handling:

By errorPage and isErrorPage attributes of page directive

By <error-page> element in web.xml file

Page 73: Java/Servlet/JSP/JDBC

Expression Language (EL) in JSPThe Expression Language (EL) simplifies the accessibility of data stored in the Java Bean component, and other objects like request, session, application etc.There are many implicit objects, operators and reserve words in EL.

Syntax for Expression Language (EL)

${ expression }  Implicit Objects in Expression Language (EL)

pageScope requestScope sessionScope param

Page 74: Java/Servlet/JSP/JDBC

Simple example of Expression Language<form action="process.jsp">  

Enter Name:<input type="text" name="name“ >

  <input type="submit" value="go"/>  

</form> 

process.jsp

Welcome, ${ param.name }  

Page 75: Java/Servlet/JSP/JDBC

Custom TagFor creating any custom tag, we need to follow following steps:

Create the Tag handler class and perform action at the start or at the end of the tag.

Create the Tag Library Descriptor (TLD) file and define tags

Create the JSP file that uses the Custom tag defined in the TLD file

Page 76: Java/Servlet/JSP/JDBC

Understanding flow of custom tag in jsp

Page 77: Java/Servlet/JSP/JDBC

Create the Tag handler classTo create the Tag Handler, we are inheriting the TagSupport class and overriding its method doStartTag().To write data for the jsp, we need to use the JspWriter class.The PageContext class provides getOut() method that returns the instance of JspWriter class. TagSupport class provides instance of pageContext bydefault.

public class MyTagHandler extends TagSupport

{    

public int doStartTag() throws JspException 

{  

JspWriter out=pageContext.getOut();

}

}

Page 78: Java/Servlet/JSP/JDBC

Create the TLD fileTag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained inside the WEB-INF directory.

<taglib>      

<tag>  

<name>today</name>  

<tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>  

</tag>  

</taglib>  

Page 79: Java/Servlet/JSP/JDBC

Create the JSP fileLet's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended to use the uri name instead of full path of tld file. We will learn about uri later. It uses taglib directive to use the tags defined in the tld file.

<%@ taglib uri="WEBINF/mytags.tld" prefix="m" %>  

<m:today>Current Date and Time is: </m:today>  

Page 80: Java/Servlet/JSP/JDBC

DATA BASE CONNECTION

Page 81: Java/Servlet/JSP/JDBC

INTRODUCTION

Database Management System or DBMS in short, refers to the technology of storing and retrieving users data with utmost efficiency along with safety and security features.

DBMS allows its users to create their own databases which are relevant with the nature of work they want. These databases are highly configurable and offers bunch of options.

Page 82: Java/Servlet/JSP/JDBC

DATABASE

A Database is a collection of related data organized in a way that data can be easily accessed, managed and updated.

Any piece of information can be a data.

Ex: Name of a student, age, class and her subjects can be counted as data for recording purposes.

Page 83: Java/Servlet/JSP/JDBC

OVERVIEW

A DBMS is a software that allows creation, definition and manipulation of database.

DBMS is actually a tool used to perform any kind of operation on data in database.

DBMS also provides protection and security to database. It maintains data consistency in case of multiple users.

Here are some examples of popular dbms, MySql, Ms sql, Oracle, Sybase, Microsoft Access and IBM DB2 etc.

Page 84: Java/Servlet/JSP/JDBC

ARCHITECTURE

Database architecture is logically divided into two types. Logical two-tier Client / Server architecture Logical three-tier Client / Server architecture

Page 85: Java/Servlet/JSP/JDBC

LOGICAL TWO-TIER CLIENT / SERVER ARCHITECTURE

The two-tier architecture is like client server application. The direct communication takes place between client and server. There is no intermediate between client and server.

Advantages: Understanding and maintenances

is easier.Disadvantages: Performance will be reduced

when there are more users.

Page 86: Java/Servlet/JSP/JDBC

LOGICAL THREE-TIER CLIENT / SERVER ARCHITECTURE

Three tier architecture having three layers.

1. Client layer

2. Business layer

3. Data layer

Page 87: Java/Servlet/JSP/JDBC

1. Client layer: Here we design the form using textbox, label etc.

2. Business layer: It is the intermediate layer which has the functions for client layer and it is used to make communication faster between client and data layer. It provides the business processes logic and the data access.

3. Data layer: it has the database.

Advantageso Easy to modify with out affecting other modules o Fast communication o Performance will be good in three tier architecture.

Page 88: Java/Servlet/JSP/JDBC

COMPONENTS OF DATABASE SYSTEM

The database system can be divided into four components.

1. Users

2. Database application

3. DBMS

4. Database

Page 89: Java/Servlet/JSP/JDBC

COMPONENTS OF DATABASE SYSTEM

USERS: User may be of various types such as

DB administrator, system developer and end user.

DATABASE APPLICATION: It may be personal, Departmental, enterprise and Internal

DBMS: Software that allow user to define, create and manages database access. Ex, MySql, oracle, etc.

DATABASE: Collection of logical data

Page 90: Java/Servlet/JSP/JDBC

FUNCTIONS

Provides data Independence. Concurrency Control. Provide Recovery Services. Provides Utility Services. Provides a clear and logical view of the process.

Page 91: Java/Servlet/JSP/JDBC

ADVANTAGES

Minimal data duplicity. Easy retrieval of data. Reduced development time and maintenance need. Minimal Data Redundancy. Data Consistency. Data Sharing. Better Controls. Reduced Maintenance

Page 92: Java/Servlet/JSP/JDBC

DISADVANTAGES

Complexity Costly Large in size

Page 93: Java/Servlet/JSP/JDBC

RDBMS

RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

Page 94: Java/Servlet/JSP/JDBC

DATA DEFINITION LANGUAGE

SQL uses the following set of commands to define database schema:

CREATE DROP ALTER TRUNCATE

CREATE: Creates new databases, tables and views from RDBMS

Create database dbms;

Create table article(id int , name varchar)

Create view for students;

Page 95: Java/Servlet/JSP/JDBC

DROP: Drop commands deletes views, tables and databases from RDBMS

Drop object type object name;

Drop database dbms;

Drop table article;

Drop view for_students;

ALTER: Modifies database schema.

Alter object_type object_name parameters;

for example:

Alter table article add subject varchar;

Page 96: Java/Servlet/JSP/JDBC

DATA MANIPULATION LANGUAGE

DML modifies the database instance by inserting, updating and deleting its data.

DML is responsible for all data modification in databases.

SQL contains the following set of command in DML section:

INSERT UPDATE DELETE SELECT

Page 97: Java/Servlet/JSP/JDBC

INSERT

INSERT: Insert command is used to insert data into a table.

Syntax: INSERT into table_name values(data1,data2,…)

Page 98: Java/Servlet/JSP/JDBC

UPDATE

The UPDATE statement is used to update records in a table.

Syntax update table_name set

column1=value1,column2=value2,...where some_column=some_value;

FOR EXAMPLE:update Students set age=18 where s_id=102;

Page 99: Java/Servlet/JSP/JDBC
Page 100: Java/Servlet/JSP/JDBC

DELETE

Delete command is used to delete data from a table.

Delete command can use to delete a particular row or whole data in the table.

Syntax: DELETE FROM table_name

WHERE some_column=some_value;To delete all row from a table. DELETE FROM table_name;

orDELETE * FROM table_name;

Page 101: Java/Servlet/JSP/JDBC
Page 102: Java/Servlet/JSP/JDBC

SELECT

This command is used to select data from database.

Syntax SELECT

column_name,column_nameFROM table_name;andSELECT * FROM table_name;

Page 103: Java/Servlet/JSP/JDBC

DATA CONTROL LANGUAGE (DCL)

Data Control Language(DCL): Is a Structured query that allows database administrators to configure security access to relational databases.

DCL commands are used to enforce database security in a multiple user database environment.

There are two types of DCL commands. GRANT REVOKE

Page 104: Java/Servlet/JSP/JDBC

GRANT

SQL GRANT is a command used to provide access or privileges on the database objects to the users.

The Syntax for the GRANT command is:

grant privilege_name on object_name to {user_name |public|role_name} [WITH GRANT OPTION];

To allow a user to create a session. grant create session to username

Page 105: Java/Servlet/JSP/JDBC

REVOKE

The REVOKE command removes user access rights or privileges to the database objects.

The syntax for this command is defined as follows:

REVOKE[GRANT OPTION FOR] [permission] ON [object] FROM [user]

Page 106: Java/Servlet/JSP/JDBC

KEY

• Key --> The attribute used to define a required item

Types of keys: * Primary Key: Key used to uniquely identify a record

* Foreign Key: A field in this table which is the Primary key of another table

Page 107: Java/Servlet/JSP/JDBC

END