SERVLETS (2).pptxintroduction to servlet with all servlets

RadhikaP41 18 views 124 slides Mar 11, 2025
Slide 1
Slide 1 of 124
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124

About This Presentation

servlets


Slide Content

UNIT3-SERVLETS Building a Web Application in Eclipse, Introduction to Servlets: Lifecycle of a Servlet,The Servlet API, Reading Servlet parameters, Reading initialization parameters, Handling HTTP Request & Responses, writing and deploying Servlets, Session management using Hidden fields, Cookies and sessions and URL rewriting, Request Dispatcher, Connecting to a database from servlet using JDBC.

Understanding Client and Server Side Scripting Web-Site Structure 2 Steps Request Content(Client) Get response back(Server) Additional Steps 1.x Execute a script in the client side 2.x: Execute a script in the server side Calculate something Retrieve data from a database 3. Execute script in the client side

Client Server

Definition Client Side Scripting computer programs on the web that are executed client-side , by the user's web browser JavaScript Jquery VBScript Server Side Scripting computer programs on the web that are executed server -side usually used to provide interactive web sites that interface to databases or other data stores PHP Perl Ruby JSP Servlets 4

Web Server

What is a Web Server? A web server is a system that delivers content(web pages) or services to end users over the internet. The basic objective of the web server is to store, process and deliver web pages to the users. This intercommunication is done using Hypertext Transfer Protocol (HTTP).

Program that understands the HTTP protocol and generates appropriate responses Clients “ connect ” to the machine Clients send a “ request ” Server reads request, generates “ response ” Client interprets response appropriately What is a Web Server?

Web Servers Popular Web Servers Apache Windows IIS IBM Websphere Apache server is the most common web server available in the market. Apache is an open source software that handles almost 70 percent of all websites available today.

Provide HTTP port number : 8080

What is web application? A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML. The web components typically execute in Web Server and respond to HTTP request.

CGI(Common Gateway Interface)

Disadvantages of CGI If number of clients increases, it takes more time for sending response. It uses platform dependent language e.g. C, C++, perl. For each request CGI Server receives, It creates new Operating System Process . If the number of requests from the client increases then more time it will take to respond to the request. As programs executed by CGI Script are written in the native languages such as C, C++, perl which are platform dependent.

Servlet

Advantages of Servlet Performance The performance of servlets is superior to CGI because there is no process creation for each client request. Each request is handled by the servlet container process. After a servlet has completed processing a request, it stays resident in memory, waiting for another request. Portability Like other Java technologies, servlet applications are portable. Rapid development cycle As a Java technology, servlets have access to the rich Java library that will help speed up the development process. Robustness Servlets are managed by the Java Virtual Machine. Don't need to worry about memory leak or garbage collection, which helps you write robust applications. Widespread acceptance Java is a widely accepted technology.

Life Cycle of Servlet Initialization init() Service service() doGet () doPost () doDelete () doHead () doTrace () doOptions () Destruction destroy() Concurrent Threads of Execution

Life Cycle Methods init() : Servlet loads and initializes the servlet service(): Servlet handles one or more client Request and Responses to the client destroy (): Servlet is deactivated or server is terminated Memory allocated for the servlet and its object are garbage collected Note : All above methods are inherited from GenericServlet class

public void service( ServletRequest req,ServletResponse res) throws ServletException,IOException { res.setContentType ("text/html"); // server responds in HTML format PrintWriter out= res.getWriter (); }

Sample Servlet Example import java.io.*; import javax.servlet .*; public class ServletExample extends GenericServlet { public void service( ServletRequest req,ServletResponse res) throws ServletException,IOException { res.setContentType ("text/html"); // server responds in HTML format PrintWriter out= res.getWriter (); out.println ("<html>"); out.println ("<body>"); out.println ("Hello World..."); out.println ("</body>"); out.println ("</html>"); } }

Directory Structure ROOT Save .java program

Web.xml(Deployment Descriptor) is an XML document that defines everything about your application that a server needs to know 

Web.xml(Deployment Descriptor file)

ServletContext and ServletConfig Both  ServletContext  and  ServletConfig  are basically the configuration objects which are used by the servlet container to initialize the various parameter of a web application. But they have some difference in terms of scope and availability. Difference between ServletConfig vs. ServletContext

An object of ServletConfig is createdby the web container for each servlet. This object can be used to get configuration information from web.xml file. If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.

ServletConfig ServletContext ServletConfig object is one per servlet class. ServletContext object is global to the entire web application. Object of ServletConfig will be created during the initialization process of the servlet. Object of ServletContext will be created at the time of web application deployment We have to give the request explicitly in order to create the ServletConfig object for the first time. ServletContext object can be available even before giving the first request. Scope: As long as a servlet is executing, the ServletConfig object will be available, it will be destroyed once the servlet execution is completed. Scope: As long as a web application is executing, the ServletContext object will be available, and it will be destroyed once the application is removed from the    server . ServletConfig object is used while only one servlet requires information shared by it. ServletContext object is used while application requires information shared by it. getServletConfig() method is used to obtain Servletconfig object. getServletContext() method is used to obtain ServletContext object. In web.xml — tag will be appear under tag. In web.xml — tag will be appear under tag.

Reading Initialization paramters Sometimes we may have a requirement that a value keeps changing time to time and so we do not want to hard code it into a servlet. If it is done, we will have to change the value and again recompile the servlet. ServletConfig   config = getServletConfig ();    String name= config.getInitParameter (“ uname ");

Deployment Descriptor file(Web.xml) <web-app>     <servlet>   <servlet-name> DemoServlet </servlet-name>   <servlet- class > DemoServlet </servlet- class >      < init-param >   < param -name> uname </ param -name>   < param -value> scott </ param -value>   </ init-param >      </servlet>    <servlet-mapping>   <servlet-name> DemoServlet </servlet-name>   < url -pattern>/servlet1</ url -pattern>   </servlet-mapping>      </web-app>  

Reading Init Parameters web.xml <web-app> <servlet> <servlet-name>Config</servlet-name> <servlet-class> ConfigDemo </servlet-class> < init -param> <param-name>username</param-name> <param-value> vnrvjiet </param-value> </ init -param> </servlet> <servlet-mapping> <servlet-name>Config</servlet-name> < url -pattern>/welcome</ url -pattern> </servlet-mapping> </web-app>

ConfigDemo.java // Import required java libraries import java.io.*; import javax.servlet .*; import javax.servlet.http .*; // Extend HttpServlet class public class ConfigDemo extends HttpServlet { public void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { // Set response content type response.setContentType ("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter (); //get ServletConfig object. ServletConfig config= getInitServletConfig (); //get init parameter from ServletConfig object. String name= config.getParameter ("username"); out.println ("Welcome "+name); out.close () }}

Reading Initialization Parameters in multiple import   javax.servlet.http.HttpServlet ;   import   javax.servlet.http.HttpServletRequest ;   import   javax.servlet.http.HttpServletResponse ;   public   class   DemoServlet   extends   HttpServlet  {   public   void   doGet ( HttpServletRequest  request,  HttpServletResponse  response)            throws   ServletException ,  IOException  {          response.setContentType ("text/html");        PrintWriter  out =  response.getWriter ();          ServletConfig  config= getServletConfig ();       Enumeration<String> e= config.getInitParameterNames ();        String str="";        while ( e.hasMoreElements ()){        str = e.nextElement ();        out.print ("< br >Name: "+ str );        out.print (" value: "+ config.getInitParameter ( str ));       }       out.close ();  }      }  

Reading Servlet Parameters <html> <body> <form action = " HelloForm " method = "GET"> First Name: <input type = "text" name = " first_name "> < br /> Last Name: <input type = "text" name = " last_name " /> <input type = "submit" value = "Submit" /> </form> </body> </html>

How to read servlet parameters // Get enumeration of parameter names. Enumeration e = request.getParameterNames (); // Display parameter names and values. while( e.hasMoreElements ()) { String pname = (String) e.nextElement (); pw.print ( pname + " = "); String pvalue = request.getParameter ( pname ); pw.println ( pvalue ); }

// Import required java libraries import java.io.*; import javax.servlet .*; import javax.servlet.http .*; // Extend HttpServlet class public class HelloForm extends HttpServlet { // Method to handle GET method request. public void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { // Set response content type response.setContentType ("text/html"); PrintWriter out = response.getWriter (); out.println ("<html>" +"< ul >\n" +”<li><b>First Name</b>: "+ request.getParameter (" first_name ") + "\n" +" <li><b>Last Name</b>: " + request.getParameter (" last_name ") + "\n" + "</ ul >\n" + " </html>" ); }

Javax.servlet.http package

The HttpServletRequest Interface The HttpServletRequest interface enables a servlet to obtain information about a client request. The HttpServletResponse Interface The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.

The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session.. All of these methods throw an IllegalStateException if the session has already been invalidated.

Why use Session Tracking? To recognize the user  It is used to recognize the particular user. Session Tracking Techniques There are four techniques used in Session tracking: Cookies Hidden Form Field URL Rewriting HttpSession

The names and values of cookies are stored on the user’s machine. Some of the information that is saved for each cookie includes the following: • The name of the cookie • The value of the cookie • The expiration date of the cookie • The domain and path of the cookie

11/6/2011 62 [email protected]

Creating Cookie Program Index.html <form method="post" action=" validate "> Name:<input type="text" name="user" />< br /> Password:<input type="text" name="pass" >< br /> <input type="submit" value="submit"> </form> 11/6/2011 63 [email protected]

MyServlet.java import java.io.*; import javax.servlet .*; import javax.servlet.http .*; public class MyServlet extends HttpServlet { protected void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { response.setContentType ("text/ html;charset =UTF-8"); String name = request.getParameter ("user"); String pass = request.getParameter ("pass"); if( pass.equals ("1234")) { Cookie ck = new Cookie(" username",name ); response.addCookie ( ck ); response.sendRedirect ("First"); } } } 64

First.java import java.io.*; import javax.servlet .*; import javax.servlet.http .*; public class First extends HttpServlet { protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { response.setContentType ("text/html "); PrintWriter out = response.getWriter (); Cookie[] cks = request.getCookies (); out.println ("Welcome "+ cks [0]. getValue ()); } } 11/6/2011 65 [email protected]

<web-app...> <servlet> <servlet-name>validate</servlet-name> <servlet-class> MyServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>validate</servlet-name> < url -pattern>/validate</ url -pattern> </servlet-mapping> <servlet> <servlet-name>First</servlet-name> <servlet-class>First</servlet-class> </servlet> <servlet-mapping> <servlet-name>First</servlet-name> < url -pattern>/First</ url -pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> 66

HTTP Session A session contains information specific to a particular user across the whole application. When a user enters into a website (or an online application) for the first time HttpSession is obtained via request.getSession (), the user is given a unique ID to identify his session. The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t specify the value in tag. This means that when the user doesn’t visit web application time specified, the session is destroyed by servlet container. The subsequent request will not be served from this session anymore, the servlet container will create a new session. 11/6/2011 67 [email protected]

Commonly used Methods of Servlet HttpSession setAttribute (String name, Object value) : Binds an object to this session, using the name specified. setMaxInactiveInterval (int interval) : Specifies the time, in seconds, between   client  requests before the servlet container will invalidate this session. getAttribute (String name) : Returns the object bound with the specified name in this session, or null if no object is bound under the name. getAttributeNames () : Returns an Enumeration of String objects containing the names of all the objects bound to this session. getId () : Returns a string containing the unique identifier assigned to this session. invalidate() : Invalidates this session then unbinds any objects bound to it. removeAttribute (String name) : Removes the object bound with the specified name from this session. 11/6/2011 68 [email protected]

sessionemo.html <html> <head> <title>session Demo</title> </head> <body> <form action="servlet1" method="post"> Enter Your Name:<input type="text" name=" userName "/>< br />< br /> <input type="submit" value="SUBMIT"/> </form> </body> </html> 11/6/2011 69 [email protected]

SetSessionServlet.java import java.io.*; import javax.servlet .*; import javax.servlet.http .*; public class SetSessionServlet extends HttpServlet { public void doPost ( HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType ("text/html"); PrintWriter out = response.getWriter (); String name= request.getParameter (" userName "); // Create a session object. HttpSession session = request.getSession (true); session.setAttribute (" uname ",name); 11/6/2011 70 [email protected]

//creating submit button out.print ("< br ><form action='servlet2' method='post'>"); out.print ("<input type='submit' value='View the session'>"); out.print ("</form>"); out.close (); } catch(Exception e){ System.out.println (e); } }} 11/6/2011 71 [email protected]

GetSessionServlet.java import java.io.*; import javax.servlet .*; import javax.servlet.http .*;  public class GetSessionServlet extends HttpServlet { public void doPost ( HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType ("text/html"); PrintWriter out = response.getWriter (); HttpSession session= request.getSession (false); String name=(String) session.getAttribute (" uname "); out.print ("Hello!.. Welcome "+name); out.close (); }catch(Exception e){ System.out.println (e); } }} 11/6/2011 72 [email protected]

11/6/2011 73 [email protected] web.xml <web-app> <servlet> <servlet-name>set</servlet-name> <servlet-class> SetSessionServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>set</servlet-name> < url -pattern>/servlet1</ url -pattern> </servlet-mapping> <servlet> <servlet-name>get</servlet-name> <servlet-class> GetSessionServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>get</servlet-name> < url -pattern>/servlet2</ url -pattern> </servlet-mapping> </web-app>  

11/6/2011 [email protected] 74

Hidden Form field <form method="post" action=" validate "> Name:<input type="text" name="user" />< br /> Password:<input type="text" name="pass" >< br /> <input type="submit" value="submit"> </form>  75

First.java import java.io.*; import javax.servlet .*; import javax.servlet.http .*; public class First extends HttpServlet { protected void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { response.setContentType ("text/ html;charset =UTF-8"); PrintWriter out = response.getWriter (); //getting value submitted in form from HTML file String user = request.getParameter ("user"); //creating a new hidden form field out.println ("<form action='Second'>"); out.println ("<input type='hidden' name='user' value='"+user+"'>"); out.println ("<input type='submit' value='submit' >"); out.println ("</form>"); } } 76

Second.java import java.io.*; import javax.servlet .*; import javax.servlet.http .*; public class Second extends HttpServlet { protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { response.setContentType ("text/ html;charset =UTF-8"); PrintWriter out = response.getWriter (); //getting parameter from the hidden field String user = request.getParameter ("user"); out.println ("Welcome "+user); } } 77

Web.xml <web-app...> <servlet> <servlet-name>First</servlet-name> <servlet-class>First</servlet-class> </servlet> <servlet-mapping> <servlet-name>First</servlet-name> < url -pattern>/First</ url -pattern> </servlet-mapping> <servlet> <servlet-name>Second</servlet-name> <servlet-class>Second</servlet-class> </servlet> <servlet-mapping> <servlet-name>Second</servlet-name> < url -pattern>/Second</ url -pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> 78

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(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter () method to obtain a parameter value. 11/6/2011 [email protected] 79

Session Tracking 80

11/6/2011 [email protected] 81

Session Tracking 1.On client's first request, the Web Container generates a unique session ID and gives it back to the client with response. This is a temporary session created by web container. 2.The client sends back the session ID with each request. Making it easier for the web container to identify where the request is coming from. 3.The Web Container uses this ID, finds the matching session with the ID and associates the session with the request. 11/6/2011 [email protected] 82

Index.html <form method="post" action="Validate"> User: <input type="text" name="user" />< br /> Password: <input type="text" name="pass" >< br /> <input type="submit" value="submit"> </form> 11/6/2011 [email protected] 83

Validate.java import java.io.*; import javax.servlet .*; import javax.servlet.http .*; public class Validate extends HttpServlet { protected void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { response.setContentType ("text/html"); String name = request.getParameter ("user"); String pass = request.getParameter ("pass"); if( pass.equals ("1234")) { //creating a session HttpSession session = request.getSession (); session.setAttribute ("user", name); response.sendRedirect ("Welcome"); } } } 11/6/2011 [email protected] 84

Welcome.java import java.io.*; import javax.servlet .*; import javax.servlet.http .*; public class Welcome extends HttpServlet { protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { response.setContentType ("text/html”); PrintWriter out = response.getWriter (); HttpSession session = request.getSession (); String user = (String) session.getAttribute ("user"); out.println ("Hello "+user); }} 11/6/2011 [email protected] 85

Web.xml <web-app..> <servlet> <servlet-name>Validate</servlet-name> <servlet-class>Validate</servlet-class> </servlet> <servlet> <servlet-name>Welcome</servlet-name> <servlet-class>Welcome</servlet-class> </servlet> <servlet-mapping> <servlet-name>Validate</servlet-name> < url -pattern>/Validate</ url -pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Welcome</servlet-name> < url -pattern>/Welcome</ url -pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> 11/6/2011 [email protected] 86

Unit4 JDBC

Java Database Connectivity(JDBC) Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL statement and retrieve result from database.

JDBC in Java Jdbc is a part of JDK software so no need to install separate software for Jdbc API Jdbc API consists of two packages java.sql package javax.sql package

JDBC Architecture

JDBC Architecture consists of two layers − JDBC API: This provides the application- to- JDBC Manager connection. JDBC Driver API: This supports the JDBC Manager- to- Driver Connection. The JDBC API uses a driver manager and database- specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source.

JDBC Driver JDBC Driver is a software component that enables java application to interact with the database. Types of drivers JDBC- ODBC bridge driver Native- API driver (partially java driver) Network Protocol driver (fully java driver) Thin driver (fully java driver)

Type 1 : JDBC- ODBC Bridge Driver The JDBC- ODBC is also known as Type 1 driver. The JDBC- ODBC bridge driver converts the JDBC method call into the ODBC function call. This driver is platform dependent. Sun provides the JDBC- ODBC Bridge driver by following URL - “sun.jdbc.odbc.JdbcOdbcDriver” Advantage Easy to use Allow easy connectivity to all database supported by the ODBC Driver. Disadvantage Slow execution time Dependent on ODBC Driver.

Type 2 : Native API Driver (Partial Java driver) The Native API driver is also known as Type 2 driver. It uses the client- side libraries of the database. must be installed on each client system. This driver converts the JDBC method call into native call of database.

Advantage faster as compared to Type- 1 Driver Disadvantage Requires native library Type 2 driver is platform dependent. It does not support applet programming.

Type 3 : Network Protocol Driver The Network protocol driver uses the three- tier model. The middle tier is responsible to converts JDBC calls directly or indirectly into vender specific database protocol . This type of driver is very flexible that is a single driver can actually provide access to multiple databases.

Advantage Does not require any native library to be installed. Database Independency. Disadvantage Slow due to increase number of network call.

Type 4 : Thin driver (Pure Java driver) It is a pure Java driver which connects all Java drivers directly to the vendor specific database protocol. This driver provides the highest performance driver for the database. Thin driver is completely written in Java because of that it is known as 100% pure Java driver.

JDBC - SQL Syntax Create Database CREATE DATABASE DATABASE_NAME; Create a Database named EMP ? CREATE DATABASE EMP; Drop Database DROP DATABASE DATABASE_NAME; Create Table CREATE TABLE table_name ( column_name column_data_type, column_name column_data_type, column_name column_data_type ... );

CREATE TABLE Employees ( id INT NOT NULL, INT NOT NULL, age first last VARCHAR(255), VARCHAR(255), PRIMARY KEY ( id ) ); Create an employee table? INSERT Data: INSERT INTO ...); table_name VALUES (column1, column2,

Insert a new row in the Employees database created earlier ? INSERT INTO Employees VALUES (100, 18, ‘cse', ‘vnr'); SELECT Data SELECT column_name, column_name, ... FROM table_name WHERE conditions; The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators.

To select the age, first and last columns from the Employees table, where id column is 100 ? SELECT FROM WHERE first, last, age Employees id = 100; UPDATE Data UPDATE table_name SET column_name = value, WHERE conditions; column_name = value, ...

To UPDATE statement changes the age column of the employee whose id is 100 ? UPDATE Employees SET age=20 WHERE id=100; DELETE Data DELETE FROM table_name WHERE conditions; DELETE statement deletes the record of the employee whose id is 100 ? DELETE FROM Employees WHERE id=100;

Steps to connect a Java Application to Database Register the Driver Create a Connection Create SQL Statement Execute SQL Statement Closing the connection

Register the Driver Class.forName() is used to load the driver class explicitly. Example to register with JDBC- ODBC Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Create a Connection getConnection() method of DriverManager class is used to create a connection.

DriverManager class Syntax getConnection(String url) getConnection(String url, String username, String password) getConnection(String url, Properties info) Example establish connection with Oracle Driver Connection con = DriverManager.getConnection("jdbc:odbc:DSN","username", "password");

Create SQL Statement The Connection interface provides the createStatement() method to create SQL statement. Syntax: public Statement createStatement( ) throws SQLException Example: Statement stmt = con.createStatement();

Execute SQL Queries The Statement interface provides the executeQuery( ) method to execute SQL statements. Syntax: public ResultSet executeQuery(String sql) throws SQLException

Example: ResultSet rs = stmt.executeQuery("select * from students"); while (rs.next()) { System.out.println (rs.getInt(1)+" "+rs.getString(2)+" "+rs.getFloat(3)); } Closing the Connection The Connection interface provides close( ) method, used to close the connection. Example: con.close( );

Statement Interface in JDBC The Statement interface provides methods to execute queries with the database.

ResultSet Interface in JDBC The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row.

How to create JDBC Connection?

What are the types of JDBC Statements available? There are 3 types of Statements, as given below: Statement: It can be used for general- purpose access to the database. It is useful when you are using static SQL statements at runtime. PreparedStatement: It can be used when you plan to use the same SQL statement many times. The PreparedStatement interface accepts input parameters at runtime. CallableStatement: CallableStatement can be used when you want to access database stored procedures.

Connection con; PreparedStatement pstmt = con.prepareStatement("sql command"); Example: PreparedStatement pstmt = con.prepareStatement( "Insert into emp value(?, ?)" ); The each ? represent the column index number in the table. If table EMP has id, name columns, then 1st ? refer to id, 2nd ? refer to name. Afterthat we need to set the value to each ? by using the setter method from PreparedStatement interface as follows : Syntax : setXXX(ColumnIndex, value)

Methods of PreparedStatement interface

PreparedStatement Interface It represents precompiled SQL statements and stores it in a PreparedStatement object. It increases the performance of the application because the query is compiled only once. The PreparedStatement is easy to reuse with new parameters.

Creating PreparedStatement Object Syntax Connection con; PreparedStatement String sql = pstmt = con.prepareStatement("sql command"); "Select * from Student where rollNo= ?"; PreparedStatement ps = con.prepareStatement(sql);

END of JDBC
Tags