23
Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem Subject Notes # Odd Semester 2014-15 Page 1 ECS-503 Object Oriented Techniques UNIT-5 Course Jdbc ..................................................................................................................................................................... 1 Servlets ............................................................................................................................................................. 17 JDBC --> The database is the heart of any enterpries system which is used to store and retrieve the data of enterprise more efficiently. --> Frequently used databases in the enterprise system are Oracle, MySQL, SQL server and so on. --> The following are list of frequently used SQL commands to perform the required DB operations such as - creating new table at DB. - insert, Delete, update operations on DB table. - Selecting the records from DB table. 1. Create table myemp(eno number, ename varchar2(20), esal number, eaddr varchar2(30)); 2. Insert into myemp values(10, 'ramesh', 5000, 'ammerpet'); 3. Delete from myemp where esal<=4000; 4. Update myemp set esal=esal+500 where esal<=8000; 5. Select * from myemp; --> JDBC is the mechanism ie. technique provided by Sun Microsystems so that any user of java application can make use of this tecnique to have communication with any DB from java application. --> So, JDBC is used to perform the required DB operations from the java application. -> The java application which is written by user by using JDBC technique to process data in the DB is called as JDBC application. -> If the user want to develop the JDBC application then he should make use of following 3 elements of JDBC. 1. JDBC API, this API will support java application with readymade interfaces, classes provided by Sun micro systems with two packages called

Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 1

ECS-503 Object Oriented Techniques

UNIT-5

Course Jdbc ..................................................................................................................................................................... 1

Servlets ............................................................................................................................................................. 17

JDBC

--> The database is the heart of any enterpries system which is used to store and retrieve the data of

enterprise more efficiently.

--> Frequently used databases in the enterprise system are Oracle, MySQL, SQL server and so on. --> The following are list of frequently used SQL commands to perform the required DB operations such as - creating new table at DB. - insert, Delete, update operations on DB table. - Selecting the records from DB table. 1. Create table myemp(eno number, ename varchar2(20), esal number, eaddr varchar2(30)); 2. Insert into myemp values(10, 'ramesh', 5000, 'ammerpet'); 3. Delete from myemp where esal<=4000; 4. Update myemp set esal=esal+500 where esal<=8000; 5. Select * from myemp; --> JDBC is the mechanism ie. technique provided by Sun Microsystems so that any user of java application can make use of this tecnique to have communication with any DB from java application. --> So, JDBC is used to perform the required DB operations from the java application. -> The java application which is written by user by using JDBC technique to process data in the DB is called as JDBC application. -> If the user want to develop the JDBC application then he should make use of following 3 elements of JDBC. 1. JDBC API, this API will support java application with readymade interfaces, classes provided by Sun micro systems with two packages called

Page 2: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 2

java.sql package javax.sql package 2. DriverManager class, this is available in java.sql package. 3. The JDBC Driver class Object, this is called as driver object, this driver object will establish connection from java application to database, send the sql commands from java application to the db and receive data from the database to the java application through the established connection. --> The Java application may not be able to communicate with any db without using these three elements of JDBC mechanism. --> If the java application is directly communication with db by using JDBC technique then this architecture is called as 2 tier architecture of JDBC as shown in the note book. --> If the client side application is able to communicate with db with the help of server side application then this architecture is called as 3 tier architecture of JDBC. --> The server side application will make use of JDBC technique to communicate with the db and to get the data from db to server side application and then this data given to requested client side application. --> In this 3 tier architecture ,the server side application is acting as mediator between client side application and database, so this server side application is called middleware or middle tier. --> The Sun micro systems providing 2 packages called java.sql package, javax.sql package, the interfaces and classes available in this package will support java application to communicate with any database. The following are some of frequently used classes and interfaces of java.sql package ie. 1. Driver Manager class. 2. Driver interface. 3. Connection interface. 4. Statement interface. 5. ResultSet interface. 6. PreparedStatement interface. 7. CallableStatment interface. 8. ResultSetMetaData interface. --> The Driver Manager class is having one static method called "get Connection()", we can use this getConnection Method through the "class name" according to application Requirement. --> All other interfaces such as Driver, Connection are having some set of "Abstract methods" provided by Sun Micro systems without any implementation details.

Page 3: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 3

For example. --> The "Driver" interface has one abstract method called "connect" Method. - -> The Connection interface has createStatement, commit, rollback abstract methods. --> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this java.sql package. --> If the user of JDBC application wants to communication with any DB then he must create an object of "JDBC driver class", this object is called as "Driver Object". --> This Driver Object will establish connection to the DB, submit sql commands to DB and receive data from database, which means we can't communicate with DB without having this "Driver object" in JDBC application. --> If we want to create driver object then we can make use of "4 types of JDBC Driver classes" which are called as "type1, type2, type3, type4 JDBC Driver classes. --> The "type1" JDBC Drive class provided by Sun Micro Systems is available at the path of "sun.jdbc.odbc" in tools.jar file of JDK. --> This type1 JdbcOdbcDriver class is already implemented with "Driver interface" method called "connect" method by Sun Micro System, this connect method establish connection to DB, submit the sql commands to DB. --> The user of JDBC application can load this type-1 JdbcOdbcDriver class into classes segment of java application and then he can create the object of this class which is called Driver object. --> If the user of JDBC application want to use type1 JDBC driver class provided by Sun Micro systems in JDBC application to communicate with some DB such as Oracle then we must have Microsoft ODBC driver in the system. --> We can't use this type1 JDBC driver class without Microsoft ODBC driver. --> So this type 1 JDBC driver class is also called as "Bridge Driver" because this will act as a bridge between the java application and ODBC driver. --> If we want to use this type1 JDBC driver in JDBC application, then we should follow the 4 steps to communicate with oracle db to perform the required db operations from java application, this is called as architecture of type1 JDBC driver. Step1: We should configure Microsoft ODBC Driver by connecting to required db such as oracle db along with some DSN name such as "ora".

Page 4: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 4

Step2: We should load type1 JDBC driver class which is provided by Sun Micro system into the classes segment of java application, so that we can create the object of this type1 JDBC driver class. --> We should use the following java code in JDBC application to load this type1 JDBC driver class. Class classreference=Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); --> Where forName is the static method available in class called "Class" provided by Sun micro system in "java.lang" pckg, this method automatically load the respective type1 JDBC driver class called "JdbcOdbcDriver" available at respective path in "tools.jar" file into the classes segment of java application and return the ref of this loaded class file, which means returning type of this method is Class, so the signature of this method is public static Class forName (String s); --> This forName method may rise an exception called ClassNotFoundException if it is unable to load the respective driver class, this exception should be handled in JDBC application by using "try, catch" construct. Step-3: We should establish the connection to the database such as oracle database from the JDBC application and we should have implementation class of connection interface object which is simply called as "connection interface object". --> We should use the following java code in JDBC application to establish connection and to get Connection interface object. Connection con=DriverManager.getConnection("jdbc:odbc:ora", "scott", "tiger"); --> Where getConnection is static method of DriverManager class, inside this get Connection method 4 functions are performed ie. 1. The object of already loaded type1 JDBC Driver Class is created. This object is called as "Driver object" ,in this Driver object there is one implemented connect () method is available. 2. This created driver object is registered (stored) with DriverManager class. 3. The connect method available in driver object is called by passing same three strings that is URL string, username, password so that connect method of driver object will establish connection to the Oracle database through Microsoft ODBC driver and return the object of implementation class of "Connection interface " available in tools.jar into getConnection method of DriverManager class. 4. Finally this Connection object is returned to the user JDBC application by getConnection method.

Page 5: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 5

--> Where "con" is the reference variable of Connection interface which is currently referencing to the Connection interface object where there are some implemented methods are available like createstatement, commit, rollback methods. --> So, the signature of this getConnection method of DriverManager class is public static Connection getConnection (String URL, String username, String password); --> This getConnection method of DriverManager class may raise an exception called "SQLException" if it is unable to establish the connection due to some environmental problems such as if we provide wrong URL string, this exception should be handled by using try,catch construct. Step 4: We should create one Statement interface object ie. the object of implementation class of Statement interfece so that we can send required sql command to database from JDBC application and we can get the data from database into JDBC application. --> If we want to get this Statement interface object then we should call "createStatement method" available in the above Connection interface object such as Statement stmt=con.createStatement(); --> Now "stmt" is currently referencing to Statement interface object where there are some implemented methods are available like executeUpdate, executeQuery and so on. The signature of createStatement method is

public Statement createStatement(); --> Now the user of JDBC application can send the required sql commands to Oracle database from JDC application by using Statement interface object methods. SENDING SQL COMMANDS TO DATABASE FROM JDBC APPLICATION. --> We can use the following two methods available in Statement interface object which are implemented by Sun Microsystems to send the required SQL command to database ie. 1. public int executeUpdate(String s); 2. public ResultSet executeQuery(String s); --> The above execute update method available in Statement interface object is used to send the sql commands such as create, insert, update, delete SQL commands from java application to db to perform the respective database operations as shown below 1. int count=stmt.executeUpdate("create table myemp(eno number,ename varchar2(20),esal number, eaddr varchar2(20));

Page 6: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 6

--> This will create a new table at database called myemp along with respective column names, If the table is created successfully then this executeUpdate method will return -1. --> If the above table already exists in the database then it will raise an exception called SQL exception. -->This exception should be handled in the application by using try-catch construct. 2. int count=stmt.executeUpdate("insert into myemp values(10, 'ramesh', 5000, 'ameerpet')"); --> This will insert the respective new record into the database table called myemp and return 1 if the record is successively inserted, otherwise it will raise SQL exception. 3. int count= stmt.executeUpdate("delete from myemp where esal <= 4000"); --> This will delete respective record from database table called myemp and return the number of records deleted successively as an integer value, otherwise it will raise SQL exception. 4. int count = stmt.executeUpdate ("update myemp set esal=esal+500 where esal >= 3000"); --> This will update the respective records in the database table called myemp and return the number of records updated successfully as an integer value, otherwise it will raise SQL exception. The executeQuery method available in Statement interface object can be used to send the required select SQL command as a string value to the database to get the data from any database table into jdbc application as shown below 1. ResultSet rs1=stmt.executeQuery("select *from myemp"); Where executeQuery is the method available in Statement interface object that will send the respective select sql command as a string to db and return one ResultSet interface object along with the data of respective db table called myemp. --> Now rs1 is currently referencing to the ResultSet interface object in the jdbc application where the data of myemp table is available. --> Now user of jdbc application can get the values from this ResultSet interface object according to application requirement. 2. ResultSet rs2=stmt.executeQuery ("select ename, esal from myemp"); POSSIBLE TYPES OF EXCEPTIONS IN JDBC APPLICATION. --> There is a possibility of following 2 types of exceptions in every jdbc application i.e.

1. ClassNotFoundException.

Page 7: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 7

2. SQLException --> These 2 types of exceptions may be raised in jdbc application due to some environmental problems. These 2 types of exceptions should be handled by using try-catch construct. PROCEDURE FOR CONFIGURATION OF ODBC DRIVER. Go to Start of windows. Settings. Control panel. -->Administrative tools. Select Data sources(ODBC). click on add button. Select Microsoft odbc for oracle. click on finish button. Give the required DSN name such as ora. click on ok button. click on ok buttion. PRACTICAL APPLICATION. // The following practical application called DatabaseCrudeOperationsEx.java will demonstrate how to perform the database operations in the database table called myemp from JDBC application. // DatabaseCrudeOperationsEx.java import java.sql.*; import java.io.*; class DatabaseCrudeOperationsEx { public static void main(String args[]) { boolean repeat=true; while(repeat) {

Page 8: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 8

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:ora","scott","tiger"); Statement stmt=con.createStatement(); // int count=stmt.executeUpdate("create table myemp(eno number,ename varchar2(20),esal number,eaddr varchar2(30))"); // System.out.println(count); // System.out.println("\nTABLE CREATED SUCCESSFULLY"); DataInputStream stdin=new DataInputStream(System.in); while(true) { System.out.println("\nENTER EMPLOYEE NO TO BE INSERTED : "); String s=stdin.readLine(); int empno=Integer.parseInt(s); System.out.println("\nENTER EMPLOYEE NAME : "); String empname=stdin.readLine(); System.out.println("\nENTER EMPLOYEE SALARY : "); s=stdin.readLine(); float empsal=Float.parseFloat(s); System.out.println("\nENTER EMPLOYEE ADDRESS : "); String empaddress=stdin.readLine(); int count=stmt.executeUpdate("insert into myemp values("+empno+",'"+empname+"',"+empsal+",'"+empaddress+"')"); if(count>0) System.out.println("\nRECORD INSERTED SUCCESSFULLY"); else System.out.println("\nRECORD INSERTION FAILED"); System.out.println("\nENTER EMPLOYEE NO TO BE DELETED : "); s=stdin.readLine(); empno=Integer.parseInt(s); count=stmt.executeUpdate("delete from myemp where eno="+empno); if(count>0) System.out.println("\nRECORD DELETED SUCCESSFULLY"); else System.out.println("\nRECORD DELETION FAILED"); System.out.println("\nENTER EMPLOYEE NO TO BE UPDATED : "); s=stdin.readLine(); empno=Integer.parseInt(s); System.out.println("\nENTER BONUS AMOUNT : "); s=stdin.readLine(); float amt=Float.parseFloat(s); count=stmt.executeUpdate("update myemp set esal=esal +"+amt+"where eno="+empno); if(count>0) System.out.println("\nRECORD UPDATED SUCCESSFULLY"); else

Page 9: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 9

System.out.println("\nRECORD UPDATION FAILED"); System.out.println("\nDo you want to repeat [yes/no] : "); String choice=stdin.readLine(); if(!choice.equalsIgnoreCase("yes")) break; } // inner while is closed repeat=false; } // try block is closed catch(ClassNotFoundException e) { System.out.println("\nClassNotFoundException is raised, trying again..."); } catch(SQLException e) { System.out.println("\nSQLException is raised, trying again..."); } catch(IOException e) { System.out.println("\nIOException is raised, trying again..."); } // catch is closed } //outer while is closed System.out.println("\n\nBYE,BYE"); System.out.println("\nHAVE A NICE DAY"); } // main is closed } // class is closed USAGE OF ResultSet INTERFACE IN JDBC APPLICATION. --> This ResultSet interface is used in the jdbc application to get the data from any database table. --> Resultset object is the reflection of database table, this ResultSet object is an object of implementation class of ResultSet interface which is simply called as ResultSet interface object. --> The executeQuery method available in statement interface object will send the respective "select SQL command" as a string to database and this method automatically create the implementation class of ResultSet interface object along with data received from the database table such as myemp table. --> The no. of rows, the no. of columns, the order of columns created in this ResultSet object will depend on the select SQL command send to the database. --> The initial cursor position of this ResultSet object is on before first row. -> The default type of this ResultSet object created by executeQuery method is called as forward only and read-only ResultSet, which means it is non scrollable, non updatable ResultSet, which means the user of

Page 10: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 10

JDBC application cannot move the cursor position in any direction and he cannot update the values of ResultSet object. --> If the user of JDBC application want to read the values from ResultSet object row by row from top to bottom then he should use while loop in the jdbc application such as while (rs.next()) { int empno=rs.getInt(1); String empname=rs.getString(2); float empsal=rs.getFloat(3); String empaddress=rs.getString(4); ...... Some other coding to use the values. ...... } --> Where next() is the method of result set interface object that will move cursor position to very next row, if the data is available in the next row then it will return true otherwise return false, So the signature of this method is public boolean next(); --> Where getInt() is the method of ResultSet object that will return the first column value of the current row ie. the employee number value as an integer value, So the signature of this method is public int getInt(column position); --> The above while loop will read data from the ResultSet object row by row in forward direction, the cursor position of ResultSet after execution of this while loop will be on after last row ie. empty row without any data. -->This usage of non-scrollable ResultSet is explained in the practical application called NonScrollableResultSetEx.java. SCROLLABLE AND UPDATABLE ResultSet : --> The default type of ResultSet object is non-scrollable and non-updatable ResultSet. --> If we want to get some other type of ResultSet according to application requirements then we must use the following 5 static variables available in the ResultSet interface ie. 1. TYPE_FORWARD_ONLY 2. TYPE_SCROLL_SENSITIVE 3. TYPE_SCROLL_INSENSITIVE 4. CONCUR_READ_ONLY

Page 11: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 11

5. CONCUR_UPDATABLE. --> All the above 5 variables are static variables available in ResultSet interface, So we can use these variables through the interface name such as ResultSet.TYPE_FORWARD_ONLY ResultSet.TYPE_SCROLL_SENSITIVE and so on. -->We must pass the required 2 arguments to createStatement method according to the type of ResultSet required. --> The difference between scroll sensitive and scroll insensitive is if any other user modify the table data then those changes are automatically reflected into scroll sensitive ResultSet, where as changes are not reflected into scroll insensitive result set. --> If the ResultSet is scrollable and updatable type then we can scroll the cursor ie. we can move cursor of this ResultSet in any direction and also we can update ie. modify the values of this ResultSet object according to application requirement. --> We can use the following methods of ResultSet interface object to scroll the cursor position in the scrollable ResultSet ie. 1. while (rs.next()) { ....... } --> Where next() is the method of ResultSet interface object that will move the cursor position to very next row, if the data is available in next row it will return true otherwise return false, So the signature of this method is public boolean next(); 2. while (rs.previous()) --> Where previous() is the method of ResultSet interface object that will move the cursor position to previous row, if the data available in previous row then it will return true otherwise return false, So the signature of this method is public boolean previous(); 3. rs.absolute(4): --> This method will directly move cursor position to the specified 4th row irrespective of current cursor position, if 4th row is not available in the Result Set then it will return false, So the signature of this method is

Page 12: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 12

public boolean absolute(int rowposition); 4. rs.relative(4): --> This method will advance the current cursor position by 4 rows, if the current cursor position is on second row then it will move cursor position on to the 6th row, if 6th row is not available in the ResultSet then it will return false, So the signature of this method is public boolean relative (int no. of rows to be advanced); 5. rs.first(): --> This will move cursor position directly on to the 1st row, if the ResultSet is empty without any rows of data then it will return false, so the signature of this method is public boolean first(); 6. rs.last(): --> This will move cursor position directly on to the last row, if the result set is empty then it will return false, so the signature of this method is public boolean last(); 7. rs.beforeFirst(): --> This will move cursor position directly on to the before 1st row, so the signature of this method is public void beforeFirst(); 8. rs.afterLast(): --> This will move cursor position directly on to after last row, so the signature of this method is public void afterLast(); UPDATING DATA IN DATABASE TABLE WITH SCROLLABLE AND UPDATABLE ResultSet : --> If you want to update data in database table then we can send directly required update sql command to the database through executeUpdate() method available in Statement interface object without having ResultSet object.

Page 13: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 13

--> We can also update records in database table through updatable ResultSet object without sending update sql command to the database. --> We can choose any one of these 2 options according to application requirements. --> We can use the following while loop in the application to update the values of employee no 20 in the db table by modifying the values in the updatable ResultSet. while(rs.next()) { if (rs.getInt(1)==20) { rs.updateString (2,"RAMESH"); rs.updateFloat (3,8000); rs.updateString (4,"AMEERPET"); rs.updateRow(); } } --> Where updateString() is the method of ResultSet interface object that will update the second column of current row with specified string value, so the signature of the method is public void updateString(int columnposition, String s); --> Where updateRow() is the method of ResultSet interface object that will update the corresponding record in the db table called myemp along with current modified values in the ResultSet object, So the signature of this method is public void updateRow(); --> We can also use deleteRow() method of ResultSet object to delete a record from the db table through updatable ResultSet and its signature is public void deleteRow(); -->How to use this scrollable and updatable ResultSet in JDBC application is explained in the practical application called ScrollableResultSetEx.java. // The following JDBC practical example demonstrate how to use non-scrollable ResultSet to get the data from database table called myemp. import java.sql.*; class NonScrollableResultSetEx { public static void main(String args[]) {

Page 14: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 14

boolean repeat=true; while(repeat) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:ora","scott","tiger"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from myemp"); System.out.println("\nDATA OF EMPLOYEES...."); while(rs.next()) { int empno=rs.getInt(1); String empname=rs.getString(2); float empsal=rs.getFloat(3); String empaddress=rs.getString(4); System.out.println("\nEMPLOYEE NO :"+empno); System.out.println("\nEMPLOYEE NAME :"+empname); System.out.println("\nEMPLOYEE SALARY :"+empsal); System.out.println("\nEMPLOYEE ADDRESS :"+empaddress); System.out.println("\n-----------"); } // inner while is closed repeat=false; } // try is closed catch(Exception e) { System.out.println("\nEXCEPTION IS RAISED, TRYING AGAIN..."); } // catch is closed } // outer while is closed System.out.println("\n\nBYE,BYE"); System.out.println("\nHAVE A NICE DAY"); } // main is closed } // class is closed USING PreparedStatement INTERAFACE IN JDBC APPLICATION. --> Whenever we send the SQL commands along with some values to the db through the methods of statement interface object then the db engine will create Query plan for the received sql command, execute the query plan with received values to perform the respective db operations and then the query plan is destroyed. --> This will increase overhead at the db when we send the same sql command again and again because the db engine should prepare query plan again and again at the db, this will reduce the performance of the db.

Page 15: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 15

--> We should use PreparedStatement interface instead of Statement interface in the jdbc appln to reduce this overhead at the db. --> We should send required sql command along with some parameters to the db by using PreparedStatement interface object so that the db engine will prepare a query plan for respective sql command with respective parameters at the db, this prepared query plan is available at the db util jdbc appln is closed. --> We can send required parameter values to the query plan from jdbc appln whenever we want to perform the respective functions again and again at the db. --> This will reduce the overhead at db because the db engine will prepare query plan only once, the same query plan is executed again and again with different parameter values received from the jdbc appln. --> So we should prefer to use PreparedStatement interface object instead of Statement interface object just to reduce the overhead at db whenever we want to perform the same function again and again at the db. -->This is explained in the practical application called PreparedCrudeOperationsEx.java // The following practical example demonstrate how to use PreparedStatement interface in JDBC application to perform the required database operations. PreparedCrudeOperationsEx.java import java.sql.*; import java.io.*; class PreparedCrudeOperationsEx { public static void main(String args[]) { Connection con; boolean repeat=true; while(repeat) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:ora","scott","tiger"); PreparedStatement pstmt1=con.prepareStatement("insert into myemp values(?,?,?,?)"); PreparedStatement pstmt2=con.prepareStatement("delete from myemp where eno=?"); PreparedStatement pstmt3=con.prepareStatement("update myemp set esal=esal+? where eno=?"); DataInputStream stdin=new DataInputStream(System.in); while(true) { System.out.println("\nENTER EMPLOYEE NO TO BE INSERTED : "); int empno=Integer.parseInt(stdin.readLine());

Page 16: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 16

System.out.println("\nENTER EMPLOYEE NAME : "); String empname=stdin.readLine(); System.out.println("\nENTER EMPLOYEE SALARY : "); float empsal=Float.parseFloat(stdin.readLine()); System.out.println("\nENTER EMPLOYEE ADDRESS : "); String empaddress=stdin.readLine(); pstmt1.setInt(1,empno); pstmt1.setString(2,empname); pstmt1.setFloat(3,empsal); pstmt1.setString(4,empaddress); int count=pstmt1.executeUpdate(); if(count>0) System.out.println("\nRECORD INSERTED SUCCESSFULLY"); else System.out.println("\nRECORD INSERTION FAILED"); System.out.println("\nENTER EMPLOYEE NO TO BE DELETED : "); empno=Integer.parseInt(stdin.readLine()); pstmt2.setInt(1,empno); count=pstmt2.executeUpdate(); if(count>0) System.out.println("\nRECORD DELETED SUCCESSFULLY"); else System.out.println("\nRECORD DELETION FAILED"); System.out.println("\nENTER EMPLOYEE NO TO BE UPDATED : "); empno=Integer.parseInt(stdin.readLine()); System.out.println("\nENTER BONUS AMOUNT : "); float amt=Float.parseFloat(stdin.readLine()); pstmt3.setFloat(1,amt); pstmt3.setInt(2,empno); count=pstmt3.executeUpdate(); if(count>0) System.out.println("\nRECORD UPDATED SUCCESSFULLY"); else System.out.println("\nRECORD UPDATION FAILED"); System.out.println("\nDo you want to repeat [yes/no] : "); String choice=stdin.readLine(); if(!choice.equalsIgnoreCase("yes")) break; } // inner while is closed System.out.println("\nCURRENT DATA OF EMPLOYEES whose salary is <= 10000 ..."); PreparedStatement pstmt4=con.prepareStatement("select * from myemp where esal<=?"); pstmt4.setFloat(1,10000); ResultSet rs=pstmt4.executeQuery(); while(rs.next()) {

Page 17: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 17

System.out.println("\nEMPLOYEE NO :"+rs.getInt(1)); System.out.println("\nEMPLOYEE NAME :"+rs.getString(2)); System.out.println("\nEMPLOYEE SALARY :"+rs.getFloat(3)); System.out.println("\nEMPLOYEE ADDRESS :"+rs.getString(4)); System.out.println("\n--------------"); } // inner while is closed repeat=false; } // try block is closed catch(Exception e) { System.out.println("\nEXCEPTION IS RAISED, TRYING AGAIN..."); } //catch is closed } // outer while is closed System.out.println("\n\nHAVE A NICE DAY"); } //main is closed } // class is closed

SERVLETS --> Servlets is the technology used to design server side web applications, this technology is based on client server architecture and request-response architecture. -->If we want to design the server side servlet application then we should install one piece of software called Tomcat server on server system, this Tomcat server called as web server which is capable of supporting the server side web applications by using servlet technology or jsp technology. -->This Tomcat server is not called as application server, which means it can't support the server side business logic applications such as EJB applications. -->The application servers such as web logic server , sun appln server is capable of supporting either web application ie. servlets, jsp appln or business logic applications ie. ejb applications. --> The Tomcat server has the following two modules of software ie. 1.Servlet Runner ie. servlet engine, this will support server side appln by using servlets technology. 2.Jsp Runner ie. jsp engine, this will support server side appln by using jsp technology. -->Whenever we install the Tomcat server on server system then the OS will assign one specific port number ie. 8080 port no. on server system. -->This Tomcat server will provide one folder called "webapps" stands for web applications so that the user at server side can store all the server side servlet applns into this webapps folder of Tomcat server. -->The user at server side should design some classes which are called as servlet classes in servlet appln according to appln requirements by following some predefined rules.

Page 18: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 18

-->Any user at client side can make a request to the server side servlet appln through the web browser, which means the communication between the client and server based on http protocol. -->When the user at client side make a request to server side servlet appln through web browser then Tomcat server at server side automatically create the servlet object of one of the servlet class available in the servlet appln, process the client request and then send response content back to the requested client browser. --> If we want to design the servlet appln at serverside then we should know following 3 steps. 1.The architecture of servlet application. 2.How to define servlet classes in the servlet application by following some predefined rules. 3.How to provide the description about all servlet classes designed in servlet appln to Tomcat server by using some xml tags, this description is called as deployment description. ARCHITECTURE OF SERVLET APPLICATION. -->The user at server side should create one servlet application folder in webapps folder of Tomcat server. -->The user at server side should create one WEB-INF folder in the application folder, inside WEB-INF folder he should create one web.xml file and classes folder. -->The user at serverside should define some servlet classes according to appl requirements, all these servlet classes class files must be stored in the classes folder. -->The user at server side should write some xml tags in web.xml file to provide the description about all the servlet classes to Tomcat server, this description is called as deployment description. -->If the user want to create any html files in the server side servlet web application then those html files must be stored in the appl folder. -->The user at server side can store or deploy any no of servlet applications in webapps folder of Tomcat server. -->If the user at client side make a request to server side servlet web appl through the web browser available at client side then the Tomcat server ie. web server automatically create the servlet object of one of the servlet class available in the application, automatically execute the user implemented methods available in servlet object, process the client request and send response content back to the client side web browser. -->Now client side web browser will receive this response content and display it on client browser page. DIFFERENT TECHNIQUES TO DEFINE SERVLET CLASSES IN SERVLET APPLICATION -->We can use any one of 3 approaches or techniques to define server side servlet classes in server side servlet application ie.

Page 19: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 19

Approach 1: -->There is one predefined interface called Servlet available in javax.servlet package. -->We should define servlet class by implementing this Servlet interface. -->If we define the servlet class by implementing Servlet interface then we must implement the following 5 abstract methods of Servlet interface in the srvlet class, otherwise the servlet class will become as abstract class. 1.public void init(ServletConfig sc); 2.public void destroy(); 3.public void service(ServletRequest req, ServletResponse res) throws ServletException,IOException; 4.public ServletConfig getServletConfig(); 5.public String gerServletInfo(); -->The disadvantage of this technique is we must implement all 5 methods inside servlet class even though they are not really required. Approach 2 : -->There is one predefined class called GenericServlet class available in the package called javax.servlet package. -->This GenericServlet class already implements the above mentioned Servlet interface. -->In this GenericServlet class, all methods of Servlet interface are already implemented except service method, which means this service method is left as abstract method. -->If we define servlet class by extending this GenericServlet class then we must implement abstract service method inside sub class, otherwise the subclass will become as abstract class. -->If we want we can override other methods inside the sub class, but it is optional. Approach 3 : -->There is one predefined class called HttpServlet available in javax.servlet.http package. -->This HttpServlet class is the derived class from GenericServlet class, in this HttpServlet class the abstract service method is already implemented, which means service method is not abstract method in this HttpServlet class. -->There are two more concrete methods available in this HttpServlet class with following signatures ie.

Page 20: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 20

1.public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException; 2.public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException; -->Where HttpServletRequest, HttpServletResponse are predefined interfaces available in javax.servlet.http package, these are derived interfaces from ServletRequest, ServletResponse interfaces respectively. -->If we define servlet class by extending this HttpServlet class then we should override doGet, doPost methods according to application requirements. -->If we want we can also other methods such as init, destroy methods, but we are not suppose to override service method which is already implemented in HttpServlet class because it will control get, post requests made by the client browser. DEPLOYMENT DESCRIPTION : -->The user at server side should define some servlet classes in the servlet application by using any one of above 3 approaches, all these servlet classes must be stored in classes folder of the servlet application. -->This classes folder of server side servlet application will act as private folder, which means the user at client side cannot directly access these servlet classes available in classes folder. -->So, the user at server side should map some relative url pattern in web.xml file by using xml tags for every servlet class, this xml code written by user in web.xml file is called as deployment description. -->All these url patterns of the servlet application will act as indirect address to the respective servlet classes. -->If the user at client side make a request to server side application with application name and url pattern then the Tomcat server automatically read the xml code available in web.xml file, find out the servlet class name for the requested url pattern, create servlet object of the respective servlet class, process the client request and send response to client browser. LIFE CYCLE SEQUENCE OF SERVLET : -->When the client make a request to server side servlet application ie, web application with the url apttern to the GenericServlet class, then the Tomcat server ie. web server at server side automatically perform the following functions. ie. 1.It will automatically read the description available in web.xml file, find out the servlet class name against to the client requested url pattern, create the servlet object of the respective servlet class, execute init method of the servlet object to perform some initialization functions at server side, this initialization functions are performed according to code written by user at server side in init method, this process is called as instantiation and initialization phase.

Page 21: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 21

2.Automatically create request, response objects for the client at server side at some addresses. 3.Store client address details ie. client host name and port number into the request object. 4.Automatically pass the addresses of request, response objects to the user implemented service method parameters of GenericServlet, store response content into response object according to the code written by user at server side in service method, this process is called as servicing phase. 5.Automatically send the response content available in response object to the requested client browser so that the browser at server side will display this response content on client browser page. 6.It will automatically destroy request, response objects at server side and place the servlet object in one storage area called servlets pool, this servlet object is available until the server is closed. 7.If the server is closed at server side then it will automatically execute the destroy method of the servlet to perform some closing functions according to code wriiten by the user at server side in destroy method and then the servlet object is destroyed, this process is called as destruction phase. -->If the client make a request once again with sama url pattern to the same servlet then the Tomcat server at server side will take existing servlet object from servlet pool and create request, response objects for the client and perform rest of the functions to process the client request, which means that init method of servlet is not executed again. -->So, init method of servlet is executed is executed only once to perform initialization functions, destroy method is executed only once to perform some closing functions, but service method of GenericServlet is executed every time when the request is received from client to process the client request. IMPLEMENTATION OF SERVICE METHOD IN GenericServlet CLASS : -->The user at server side should implement service method in GenericServelt class to send the required html tags and plain text to the client browser. // The following practical example demonstrate how to define GenericServlet , HttpServlet classes in server side servlet application and how to map the required url patterns for those servlet classes in web.xml file. GenericServletEx.java ( This is GenericServlet class with the url pattern as /mygenericservlet ) import java.io.*; import javax.servlet.*; public class GenericServletEx extends GenericServlet { public void service(ServletRequest p,ServletResponse q) throws ServletException,IOException { q.setContentType("text/html");

Page 22: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 22

PrintWriter k=q.getWriter(); k.println("<body bgcolor=pink>"); k.println("<center>"); k.println("HELLO CLIENT"); k.println("<br><br>"); addMessage(k); k.println(“<br><br>”); k.println("WELCOME TO GENERIC SERVLET"); k.println("<br><br>"); k.println("THANK YOU<br> FOR VISITING<br>THIS APPLICATION"); k.println("<br><br><br><br>"); k.println("<br><br>"); k.println("</center>"); k.println("HAVE A NICE DAY"); k.println("<br><br>"); k.println("<center>B<br>Y<br>E<br>B<br>Y<br>E<br></center>"); k.println("</body>"); } public void addMessage(PrintWriter m) { m.println("HOW ARE YOU ?"); m.println("<br><br>"); String s="I HOPE YOU ARE FINE"; m.println(s); } } HttpServeltEx.java ( This is HttpServlet class with the url pattern as /myhttpservlet ) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HttpServletEx extends HttpServlet { int count=0; String msg="HELLO CLIENT"; String wish="HAVE A NICE DAY"; public void doGet(HttpServletRequest p,HttpServletResponse q) throws ServletException,IOException { q.setContentType("text/html"); PrintWriter m=q.getWriter(); count++; m.println("<body bgcolor=cyan>"); m.println("<center><b>"); m.println("<br><br>");

Page 23: Allenhouse Institute of Technology (UPTU Code : 505)--> The Statement interface has executeUpdate, executeQuery abstract Methods. --> The JDBC Driver class is not available in this

Allenhouse Institute of Technology (UPTU Code : 505)

OOT Notes By Hammad Lari for B.Tech CSE VthSem

Subject Notes # Odd Semester 2014-15 Page 23

m.println(msg); m.println("<br><br>"); m.println("WELCOME TO HTTP SERVLET"); m.println("<br><br>"); m.println(wish); m.println("<br><br>"); if(count>=5) { m.println("ARE YOU CRAZY ?"); m.println("<br><br>"); } for(int i=1;i<=count;i++) { m.println("BYE,BYE"); m.println("<br>"); } m.println("</b></center>"); m.println("</body>"); } } web.xml <web-app> <servlet> <servlet-name>first</servlet-name> <servlet-class>GenericServletEx</servlet-class> </servlet> <servlet-mapping> <servlet-name>first</servlet-name> <url-pattern>/mygenericservlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>second</servlet-name> <servlet-class>HttpServletEx</servlet-class> </servlet> <servlet-mapping> <servlet-name>second</servlet-name> <url-pattern>/myhttpservlet</url-pattern> </servlet-mapping> </web-app>