Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem

Size: px
Start display at page:

Download "Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem"

Transcription

1 ECS-503 Object Oriented Techniques UNIT-5 Course Jdbc... 1 Servlets 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 Subject Notes # Odd Semester Page 1

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. Subject Notes # Odd Semester Page 2

3 For example. Allenhouse Institute of Technology (UPTU Code : 505) --> 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". Subject Notes # Odd Semester Page 3

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. Subject Notes # Odd Semester Page 4

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)); Subject Notes # Odd Semester Page 5

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 > 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. Subject Notes # Odd Semester Page 6

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) Subject Notes # Odd Semester Page 7

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 Subject Notes # Odd Semester Page 8

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 Subject Notes # Odd Semester Page 9

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 Subject Notes # Odd Semester Page 10

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 Subject Notes # Odd Semester Page 11

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. Subject Notes # Odd Semester Page 12

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[]) Subject Notes # Odd Semester Page 13

14 boolean repeat=true; while(repeat) Allenhouse Institute of Technology (UPTU Code : 505) 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. Subject Notes # Odd Semester Page 14

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()); Subject Notes # Odd Semester Page 15

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 <= "); PreparedStatement pstmt4=con.preparestatement("select * from myemp where esal<=?"); pstmt4.setfloat(1,10000); ResultSet rs=pstmt4.executequery(); while(rs.next()) Subject Notes # Odd Semester Page 16

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 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. Subject Notes # Odd Semester Page 17

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. Subject Notes # Odd Semester Page 18

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. Subject Notes # Odd Semester Page 19

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. Subject Notes # Odd Semester Page 20

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"); Subject Notes # Odd Semester Page 21

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>"); Subject Notes # Odd Semester Page 22

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> Subject Notes # Odd Semester Page 23

JDBC 3.0. Java Database Connectivity. 1 Java

JDBC 3.0. Java Database Connectivity. 1 Java JDBC 3.0 Database Connectivity 1 Contents 1 JDBC API 2 JDBC Architecture 3 Steps to code 4 Code 5 How to configure the DSN for ODBC Driver for MS-Access 6 Driver Types 7 JDBC-ODBC Bridge 8 Disadvantages

More information

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22. Answers 1. What is the super interface to all the JDBC Drivers, specify their fully qualified name? a. Java.sql.Driver i. JDBC-ODBC Driver ii. Java-Native API Driver iii. All Java Net Driver iv. Java Native

More information

JAVA AND DATABASES. Summer 2018

JAVA AND DATABASES. Summer 2018 JAVA AND DATABASES Summer 2018 JDBC JDBC (Java Database Connectivity) an API for working with databases in Java (works with any tabular data, but focuses on relational databases) Works with 3 basic actions:

More information

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets JDBC Stands for Java Database Connectivity, is an API specification that defines the following: 1. How to interact with database/data-source from Java applets, apps, servlets 2. How to use JDBC drivers

More information

Top 50 JDBC Interview Questions and Answers

Top 50 JDBC Interview Questions and Answers Top 50 JDBC Interview Questions and Answers 1) What is the JDBC? JDBC stands for Java Database Connectivity. JDBC is a Java API that communicates with the database and execute SQLquery. 2) What is a JDBC

More information

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases. JDBC The JDBC TM API is the application programming interface that provides universal data access for the Java TM platform. In other words, the JDBC API is used to work with a relational database or other

More information

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Database Connection Budditha Hettige Department of Statistics and Computer Science Budditha Hettige 1 From database to Java There are many brands of database: Microsoft

More information

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4 CMPUT 391 Database Management Systems The Basic Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems

More information

SQL and Java. Database Systems Lecture 20 Natasha Alechina

SQL and Java. Database Systems Lecture 20 Natasha Alechina Database Systems Lecture 20 Natasha Alechina In this Lecture SQL in Java SQL from within other Languages SQL, Java, and JDBC For More Information Sun Java tutorial: http://java.sun.com/docs/books/tutorial/jdbc

More information

JDBC [Java DataBase Connectivity]

JDBC [Java DataBase Connectivity] JDBC [Java DataBase Connectivity] Introduction Almost all the web applications need to work with the data stored in the databases. JDBC is Java specification that allows the Java programs to access the

More information

Working with Databases and Java

Working with Databases and Java Working with Databases and Java Pedro Contreras Department of Computer Science Royal Holloway, University of London January 30, 2008 Outline Introduction to relational databases Introduction to Structured

More information

SQL in a Server Environment

SQL in a Server Environment SQL in a Server Environment Vaidė Narváez Computer Information Systems January 13th, 2011 The Three-Tier Architecture Application logic components Copyright c 2009 Pearson Education, Inc. Publishing as

More information

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview COSC 304 Introduction to Database Systems Database Programming Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Database Programming Overview Most user interaction with

More information

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Enterprise Edition Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Beans Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 2 Java Bean POJO class : private Attributes public

More information

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection. JDBC PROGRAMMING JDBC JDBC Java DataBase Connectivity Useful for database driven applications Standard API for accessing relational databases Compatible with wide range of databases Current Version JDBC

More information

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers.

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers. Q.1) What is, in terms of JDBC, a DataSource? A. A DataSource is the basic service for managing a set of JDBC drivers B. A DataSource is the Java representation of a physical data source C. A DataSource

More information

JDBC Java Database Connectivity is a Java feature that lets you connect

JDBC Java Database Connectivity is a Java feature that lets you connect Chapter 4: Using JDBC to Connect to a Database In This Chapter Configuring JDBC drivers Creating a connection Executing SQL statements Retrieving result data Updating and deleting data JDBC Java Database

More information

Web based Applications, Tomcat and Servlets - Lab 3 -

Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta The Basic Web Server CMPUT 391 Database Management

More information

UNIT III - JDBC Two Marks

UNIT III - JDBC Two Marks UNIT III - JDBC Two Marks 1.What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for databaseindependent connectivity between the Java programming language and a wide

More information

Servlet Fudamentals. Celsina Bignoli

Servlet Fudamentals. Celsina Bignoli Servlet Fudamentals Celsina Bignoli bignolic@smccd.net What can you build with Servlets? Search Engines E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications:

More information

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server. JDBC Drivers Type 1 What is JDBC Driver? JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server. For example, using JDBC drivers enable you to open database

More information

UNIT-3 Java Database Client/Server

UNIT-3 Java Database Client/Server UNIT-3 Java Database Client/Server TOPICS TO BE COVERED 3.1 Client-Server Design: Two-Tier Database Design, Three-Tier Database Design 3.2 The JDBC API: The API Components, Database Creation, table creation

More information

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal Introduction JDBC is a Java standard that provides the interface for connecting from Java to relational databases. The JDBC standard is defined by Sun Microsystems and implemented through the standard

More information

JDBC. Oracle ODBC SP API SP API. SQL server C function calls. SQL server ODBC SP API. Oracle DSN Oracle ODBC Oracle

JDBC. Oracle ODBC SP API SP API. SQL server C function calls. SQL server ODBC SP API. Oracle DSN Oracle ODBC Oracle How to Interact with DataBase? THETOPPERSWAY.COM Generally every DB vendor provides a User Interface through which we can easily execute SQL query s and get the result (For example Oracle Query Manager

More information

Introduction to JDBC. JDBC: Java Database Connectivity. Why Access a Database with Java? Compilation. Six Steps. Packages to Import

Introduction to JDBC. JDBC: Java Database Connectivity. Why Access a Database with Java? Compilation. Six Steps. Packages to Import Introduction to JDBC JDBC: Java Database Connectivity JDBC is used for accessing databases from Java applications Information is transferred from relations to objects and vice-versa databases optimized

More information

Unit 3 - Java Data Base Connectivity

Unit 3 - Java Data Base Connectivity Two-Tier Database Design The two-tier is based on Client-Server architecture. The direct communication takes place between client and server. There is no mediator between client and server. Because of

More information

O ne of the most important features of JavaServer

O ne of the most important features of JavaServer INTRODUCTION TO DATABASES O ne of the most important features of JavaServer Pages technology is the ability to connect to a Databases store and efficiently manage large collections of information. JSP

More information

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http? What are Servlets? Servlets1 Fatemeh Abbasinejad abbasine@cs.ucdavis.edu A program that runs on a web server acting as middle layer between requests coming from a web browser and databases or applications

More information

Database Application Development

Database Application Development Database Application Development Linda Wu (CMPT 354 2004-2) Topics SQL in application code Embedded SQL JDBC SQLJ Stored procedures Chapter 6 CMPT 354 2004-2 2 SQL in Application Code SQL commands can

More information

JAVA SERVLET. Server-side Programming INTRODUCTION

JAVA SERVLET. Server-side Programming INTRODUCTION JAVA SERVLET Server-side Programming INTRODUCTION 1 AGENDA Introduction Java Servlet Web/Application Server Servlet Life Cycle Web Application Life Cycle Servlet API Writing Servlet Program Summary 2 INTRODUCTION

More information

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text Learning Objectives This module gives an introduction about Java Database

More information

JDBC BASIC 19/05/2012. Objectives. Java Database Connectivity. Definitions of JDBC. Part 1. JDBC basic Working with JDBC Adv anced JDBC programming

JDBC BASIC 19/05/2012. Objectives. Java Database Connectivity. Definitions of JDBC. Part 1. JDBC basic Working with JDBC Adv anced JDBC programming Objectives Java Database Connectivity JDBC basic Working with JDBC Adv anced JDBC programming By Võ Văn Hải Faculty of Information Technologies Summer 2012 2/27 Definitions of JDBC JDBC APIs, which provides

More information

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017 Introduction to SQL Programming Techniques CSC 375, Fall 2017 The Six Phases of a Project: Enthusiasm Disillusionment Panic Search for the Guilty Punishment of the Innocent Praise for non-participants

More information

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity Objectives Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity Setting Up JDBC Before you can begin to utilize JDBC, you must

More information

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California shahabi@usc.edu 1 Overview JDBC Package Connecting to databases with JDBC Executing

More information

Application Programming for Relational Databases

Application Programming for Relational Databases Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California shahabi@usc.edu 1 Overview JDBC Package Connecting to databases with JDBC Executing

More information

DB I. 1 Dr. Ahmed ElShafee, Java course

DB I. 1 Dr. Ahmed ElShafee, Java course Lecture (15) DB I Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, Java course Agenda 2 Dr. Ahmed ElShafee, Java course Introduction Java uses something called JDBC (Java Database Connectivity) to connect to databases.

More information

Databases 2012 Embedded SQL

Databases 2012 Embedded SQL Databases 2012 Christian S. Jensen Computer Science, Aarhus University SQL is rarely written as ad-hoc queries using the generic SQL interface The typical scenario: client server database SQL is embedded

More information

Servlet 5.1 JDBC 5.2 JDBC

Servlet 5.1 JDBC 5.2 JDBC 5 Servlet Java 5.1 JDBC JDBC Java DataBase Connectivity Java API JDBC Java Oracle, PostgreSQL, MySQL Java JDBC Servlet OpenOffice.org ver. 2.0 HSQLDB HSQLDB 100% Java HSQLDB SQL 5.2 JDBC Java 1. JDBC 2.

More information

CS506 Web Design & Development Final Term Solved MCQs with Reference

CS506 Web Design & Development Final Term Solved MCQs with Reference with Reference I am student in MCS (Virtual University of Pakistan). All the MCQs are solved by me. I followed the Moaaz pattern in Writing and Layout this document. Because many students are familiar

More information

AJP. CHAPTER 5: SERVLET -20 marks

AJP. CHAPTER 5: SERVLET -20 marks 1) Draw and explain the life cycle of servlet. (Explanation 3 Marks, Diagram -1 Marks) AJP CHAPTER 5: SERVLET -20 marks Ans : Three methods are central to the life cycle of a servlet. These are init( ),

More information

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 -

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 - CMPUT 391 Database Management Systems JDBC in Review - - Department of Computing Science University of Alberta What Is JDBC? JDBC is a programming interface JDBC allows developers using java to gain access

More information

Module 4: SERVLET and JSP

Module 4: SERVLET and JSP 1.What Is a Servlet? Module 4: SERVLET and JSP A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper

More information

3) execute() Usage: when you cannot determine whether SQL is an update or query return true if row is returned, use getresultset() to get the

3) execute() Usage: when you cannot determine whether SQL is an update or query return true if row is returned, use getresultset() to get the Agenda Lecture (07) Database connectivity (II) Connecting DB Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems 2 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems The

More information

SNS COLLEGE OF ENGINEERING, Coimbatore

SNS COLLEGE OF ENGINEERING, Coimbatore SNS COLLEGE OF ENGINEERING, Coimbatore 641 107 Accredited by NAAC UGC with A Grade Approved by AICTE and Affiliated to Anna University, Chennai IT6503 WEB PROGRAMMING UNIT 03 JDBC JDBC Overview JDBC implementation

More information

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY UNIT IV SERVLETS 1. What is Servlets? a. Servlets are server side components that provide a powerful mechanism

More information

Unit-4: Servlet Sessions:

Unit-4: Servlet Sessions: 4.1 What Is Session Tracking? Unit-4: Servlet Sessions: Session tracking is the capability of a server to maintain the current state of a single client s sequential requests. Session simply means a particular

More information

Session 8. Introduction to Servlets. Semester Project

Session 8. Introduction to Servlets. Semester Project Session 8 Introduction to Servlets 1 Semester Project Reverse engineer a version of the Oracle site You will be validating form fields with Ajax calls to a server You will use multiple formats for the

More information

3. The pool should be added now. You can start Weblogic server and see if there s any error message.

3. The pool should be added now. You can start Weblogic server and see if there s any error message. CS 342 Software Engineering Lab: Weblogic server (w/ database pools) setup, Servlet, XMLC warming up Professor: David Wolber (wolber@usfca.edu), TA: Samson Yingfeng Su (ysu@cs.usfca.edu) Setup Weblogic

More information

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database Outline Lecture 10: Database Connectivity -JDBC Persistence via Database JDBC (Java Database Connectivity) JDBC API Wendy Liu CSC309F Fall 2007 1 2 Java Persistence Persistence via Database JDBC (Java

More information

Database connectivity (II)

Database connectivity (II) Lecture (07) Database connectivity (II) Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems Agenda Connecting DB 2 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems The

More information

JDBC - INTERVIEW QUESTIONS

JDBC - INTERVIEW QUESTIONS JDBC - INTERVIEW QUESTIONS http://www.tutorialspoint.com/jdbc/jdbc_interview_questions.htm Copyright tutorialspoint.com Dear readers, these JDBC Interview Questions have been designed specially to get

More information

Database Application Programs PL/SQL, Java and the Web

Database Application Programs PL/SQL, Java and the Web Database Application Programs PL/SQL, Java and the Web As well as setting up the database and running queries, it is vital to be able to build programs which manage the database although they will only

More information

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation Kyle Brown Knowledge Systems Corporation 1 What is the JDBC? What other persistence mechanisms are available? What facilities does it offer? How is it used? 2 JDBC is the Java DataBase Connectivity specification

More information

13 Creation and Manipulation of Tables and Databases

13 Creation and Manipulation of Tables and Databases 150.420 Informationslogistik SQL Handout No. 9 SS 2013 13 Creation and Manipulation of Tables and Databases 13.1 Creation and Deletion Databases can be created and deleted using respectively. CREATE DATABASE

More information

Java Database Connectivity

Java Database Connectivity Java Database Connectivity Introduction Java Database Connectivity (JDBC) provides a standard library for accessing databases. The JDBC API contains number of interfaces and classes that are extensively

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

Java Database Connectivity

Java Database Connectivity Java Database Connectivity ADVANCED FEATURES Dr. Syed Imtiyaz Hassan Assistant Professor, Deptt. of CSE, Jamia Hamdard (Deemed to be University), New Delhi, India. s.imtiyaz@jamiahamdard.ac.in Agenda Scrollable

More information

INTRODUCTION TO JDBC - Revised spring

INTRODUCTION TO JDBC - Revised spring INTRODUCTION TO JDBC - Revised spring 2004 - 1 What is JDBC? Java Database Connectivity (JDBC) is a package in the Java programming language and consists of several Java classes that deal with database

More information

INTRODUCTION TO JDBC - Revised Spring

INTRODUCTION TO JDBC - Revised Spring INTRODUCTION TO JDBC - Revised Spring 2006 - 1 What is JDBC? Java Database Connectivity (JDBC) is an Application Programmers Interface (API) that defines how a Java program can connect and exchange data

More information

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL. SQL: Programming CPS 116 Introduction to Database Systems Announcements (September 25) 2 Homework #2 due this Thursday Submit to Yi not through Jun s office door Solution available this weekend No class

More information

This lecture. Databases - JDBC I. Application Programs. Database Access End Users

This lecture. Databases - JDBC I. Application Programs. Database Access End Users This lecture Databases - I The lecture starts discussion of how a Java-based application program connects to a database using. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 1 / 24 (GF Royle 2006-8,

More information

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065)

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065) MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065) DATABASE CONNECTIVITY TO MYSQL Level- I Questions 1. What is the importance of java.sql.*; in java jdbc connection?

More information

Table of Contents. Introduction... xxi

Table of Contents. Introduction... xxi Introduction... xxi Chapter 1: Getting Started with Web Applications in Java... 1 Introduction to Web Applications... 2 Benefits of Web Applications... 5 Technologies used in Web Applications... 5 Describing

More information

Scheme G Sample Question Paper Unit Test 2

Scheme G Sample Question Paper Unit Test 2 Scheme G Sample Question Paper Unit Test 2 Course Name: Computer Engineering Group Course Code: CO/CD/CM/CW/IF Semester: Sixth Subject Title: Advanced Java Programming Marks: 25 Marks 17625 ---------------------------------------------------------------------------------------------------------------------------

More information

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets Course Name: Advanced Java Lecture 13 Topics to be covered The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets Introducing

More information

EXPERIMENT- 9. Login.html

EXPERIMENT- 9. Login.html EXPERIMENT- 9 To write a program that takes a name as input and on submit it shows a hello page with name taken from the request. And it shows starting time at the right top corner of the page and provides

More information

Java Database Connectivity (JDBC) 25.1 What is JDBC?

Java Database Connectivity (JDBC) 25.1 What is JDBC? PART 25 Java Database Connectivity (JDBC) 25.1 What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming

More information

Persistency Patterns. Repository and DAO

Persistency Patterns. Repository and DAO Persistency Patterns Repository and DAO 1 Repository pattern Basically, the Repository pattern just means putting a façade over your persistence system so that you can shield the rest of your application

More information

Accessing databases in Java using JDBC

Accessing databases in Java using JDBC Accessing databases in Java using JDBC Introduction JDBC is an API for Java that allows working with relational databases. JDBC offers the possibility to use SQL statements for DDL and DML statements.

More information

COMP102: Introduction to Databases, 23

COMP102: Introduction to Databases, 23 COMP102: Introduction to Databases, 23 Dr Muhammad Sulaiman Khan Department of Computer Science University of Liverpool U.K. 04 April, 2011 Programming with SQL Specific topics for today: Client/Server

More information

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark Database Access with JDBC Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@ase.au.dk Overview Overview of JDBC technology JDBC drivers Seven basic steps in using JDBC Retrieving

More information

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry In the name of Allah Islamic University of Gaza Faculty of Engineering Computer Engineering Department ECOM 4113 DataBase Lab Lab # 9 JAVA-DATABASE CONNECTION El-masry 2013 Objective In this lab, we turn

More information

Getting started with Winstone. Minimal servlet container

Getting started with Winstone. Minimal servlet container Getting started with Winstone Minimal servlet container What is Winstone? Winstone is a small servlet container, consisting of a single JAR file. You can run Winstone on your computer using Java, and get

More information

Unit 2 JDBC Programming

Unit 2 JDBC Programming Q1. What is JDBC? Explain the types of JDBC drivers? Ans. What is JDBC? JDBC is an API, which is used in java programming for interacting with database. JDBC (Java DataBase Connection) is the standard

More information

JdbcResultSet.java. import java.sql.*;

JdbcResultSet.java. import java.sql.*; 1)Write a program to display the current contents of the tables in the database where table name is Registration and attributes are id,firstname,lastname,age. JdbcResultSet.java import java.sql.*; public

More information

Pieter van den Hombergh. March 25, 2018

Pieter van den Hombergh. March 25, 2018 ergh Fontys Hogeschool voor Techniek en Logistiek March 25, 2018 ergh/fhtenl March 25, 2018 1/25 JDBC JDBC is a Java database connectivity technology (Java Standard Edition platform) from Oracle Corporation.

More information

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature INTRODUCTION TO SERVLETS AND WEB CONTAINERS Actions in Accord with All the Laws of Nature Web server vs web container Most commercial web applications use Apache proven architecture and free license. Tomcat

More information

Programming in Java

Programming in Java 320341 Programming in Java Fall Semester 2014 Lecture 16: Introduction to Database Programming Instructor: Slides: Jürgen Schönwälder Bendick Mahleko Objectives This lecture introduces the following -

More information

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. About the Tutorial Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire

More information

Fast Track to Java EE

Fast Track to Java EE Java Enterprise Edition is a powerful platform for building web applications. This platform offers all the advantages of developing in Java plus a comprehensive suite of server-side technologies. This

More information

Types of Databases. Types of Databases. Types of Databases. Databases and Web. Databases and Web. Relational databases may also have indexes

Types of Databases. Types of Databases. Types of Databases. Databases and Web. Databases and Web. Relational databases may also have indexes Types of Databases Relational databases contain stuctured data tables, columns, fixed datatype for each column Text databases are available for storing non-structured data typically text databases store

More information

PERSİSTENCE OBJECT RELATİON MAPPİNG

PERSİSTENCE OBJECT RELATİON MAPPİNG PERSİSTENCE Most of the applications require storing and retrieving objects in a persistent storage mechanism. This chapter introduces how to store and retrieve information in a persistent storage with

More information

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle Introduction Now that the concept of servlet is in place, let s move one step further and understand the basic classes and interfaces that java provides to deal with servlets. Java provides a servlet Application

More information

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200 Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200 1 SQL code in other programming languages SQL commands can be called from within a host language (e.g., C++ or Java) program.

More information

Chapter 16: Databases

Chapter 16: Databases Chapter 16: Databases Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 16 discusses the following main topics: Introduction to Database

More information

The Servlet Life Cycle

The Servlet Life Cycle The Servlet Life Cycle What is a servlet? Servlet is a server side component which receives a request from a client, processes the request and sends a content based response back to the client. The Servlet

More information

SQL: Programming Midterm in class next Thursday (October 5)

SQL: Programming Midterm in class next Thursday (October 5) Announcements (September 28) 2 Homework #1 graded Homework #2 due today Solution available this weekend SQL: Programming Midterm in class next Thursday (October 5) Open book, open notes Format similar

More information

Database Applications (15-415)

Database Applications (15-415) Database Applications (15-415) SQL-Part III & Storing Data: Disks and Files- Part I Lecture 8, February 5, 2014 Mohammad Hammoud Today Last Session: Standard Query Language (SQL)- Part II Today s Session:

More information

Web Applications and Database Connectivity using JDBC (Part II)

Web Applications and Database Connectivity using JDBC (Part II) Web Applications and Database Connectivity using JDBC (Part II) Advanced Topics in Java Khalid Azim Mughal khalid@ii.uib.no http://www.ii.uib.no/~khalid/atij/ Version date: 2007-02-08 ATIJ Web Applications

More information

Chapter #1. Program to demonstrate applet life cycle

Chapter #1. Program to demonstrate applet life cycle Chapter #1. Program to demonstrate applet life cycle import java.applet.applet; import java.awt.*; public class LifeCycle extends Applet{ public void init(){ System.out.println(" init()"); public void

More information

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science mluckner@mini.pw.edu.pl http://www.mini.pw.edu.pl/~lucknerm } JDBC ("Java Database Connectivity ) is a set

More information

Lab # 9. Java to Database Connection

Lab # 9. Java to Database Connection Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Lab # 9 Java to Database Connection Eng. Haneen El-Masry December, 2014 2 Objective In this lab, we turn

More information

JDBC Programming: Intro

JDBC Programming: Intro JDBC Programming: Intro Most interaction with DB is not via interactive interface Most people interact via 1. Application programs directly 2. Apps over the internet There are 3 general approaches to developing

More information

Lecture 2. Introduction to JDBC

Lecture 2. Introduction to JDBC Lecture 2 Introduction to JDBC Introducing JDBC According to Sun, JDBC is not an acronym, but is commonly misinterpreted to mean Java DataBase Connectivity JDBC: is an API that provides universal data

More information

Visit for more.

Visit  for more. Chapter 6: Database Connectivity Informatics Practices Class XII (CBSE Board) Revised as per CBSE Curriculum 2015 Visit www.ip4you.blogspot.com for more. Authored By:- Rajesh Kumar Mishra, PGT (Comp.Sc.)

More information

Accessing a database from Java. Using JDBC

Accessing a database from Java. Using JDBC Accessing a database from Java Using JDBC We ve got a fuzzbox and we re gonna use it Now we know a little about databases and SQL. So how do we access a database from a Java application? There is an API

More information

Advanced Web Technology

Advanced Web Technology Berne University of Applied Sciences Dr. E. Benoist Winter Term 2005-2006 Presentation 1 Presentation of the Course Part Java and the Web Servlet JSP and JSP Deployment The Model View Controler (Java Server

More information

Backend. (Very) Simple server examples

Backend. (Very) Simple server examples Backend (Very) Simple server examples Web server example Browser HTML form HTTP/GET Webserver / Servlet JDBC DB Student example sqlite>.schema CREATE TABLE students(id integer primary key asc,name varchar(30));

More information

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests What is the servlet? Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently.

More information