0% found this document useful (0 votes)
47 views

Dbms Mod3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
47 views

Dbms Mod3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
‘The concept of a joined table (or joined relation) was incorporated into SQL to permit users to specify a table resulting from a join operation in the FROM clause of a query. This construct may be easier to comprehend than mixing together all the select and join conditions in the WHERE clause. For example, consider query QU, which retrieves the name and address of every employee who works for the ‘Research’ department. It may be easier to specify the join of the EMPLOYEE and DEPARTMENT relations first, and then to select the desired tuptes and attributes. This can be written in SQL. as in QUA: QUA: SELECT Fname,Lname, Address FROM (EMPLOYEE JOIN DEPARTMENT ON Dno=Dnumber) WHEREDname—"Research’; ‘TheFROMclause in Q1Acontains 2 single joined table-The attributes of such a table are all the attributes of the first table, EMPLOYEE, followed by all the attributes of the second table, DEPARTMENT. The concept of a joined table also allows the user to specify different types of join, such as NATURAL, JOIN and various types of OUTER JOIN. In a NATURAL JOIN on two relations RandS.no join condition is specified:an implicit EQUIIOIN condition for each pair of attributes with the same name from R and Sis created. Each such pair of attributes is included only once in the resulting relation. If the names of the join attributes are not the same in the base relations, itis possible to rename the attributes so that they match.and then to apply NATURAL JOIN.In this case, the AS construct can be used to rename a relation and all its attributes in the FROM clause. This is illustrated in QIB, where the DEPARTMENT relation is, renamed as DEPT and ity attributes are renamed as Dame, Dno (to match the name of the desired join attribute Dno in the EMPLOYEE table), Mssn, and Msdate. The implied join condition for this NATURAL JOIN is EMPLOYEE. Dno=DEPT.Dno, because this is the only pair of attributes with the same name after renaming: QIB: SELECT Fame, Lname, Address FROM. (EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT (Dname, Dno, Mss. Msdate))) WHERE Dname="Research’; ‘The default type of join in a joined table is called an inner, if a matching tuple exists in the other relation pe «are a variety of outer join operations. LEFT OUTER JOIN (every tuple in the left table must appear in the resultif it does not have a ‘matching tuple,it is padded with NULL values for the attributes of the right table). in, where a tuple is included in the result only 2 RIGHT OUTER JOIN (every tuple in the right table must appear in the resultif it does not have a matching tuple.it is padded with NULL values for the attributes of the left table). 3) FULL OUTER JOIN :It is a combination of left and right outer joins In the latter three options, the keyword OUTER may be omitted.{f the join attributes have the same ‘name,one can also specify the natural join variation of outer joins by using the keyword NATURAL before the operation (for example, NATURAL LEFT OUTER JOIN). The keyword CROSS JOIN is used to specify the CARTESIAN PRODUCT operationalthough this should be used only with the utmost care because it generates all possible tuple combinations. It is also possible to nest join specifications; that is, one of the tables in a join may itself be a joined table. This allows the specification of the join of three or more tables as a single joined table, which is called a multiway Join. EX: SELECT Pnumber, Daum, Lname, Address, Bdate SUNIL G L, Asst.Professor, Dept of CSE,SVIT. Page 5 MODULE -III NOTES DBMS -18CS53 FROM (PROJECT JOIN DEPARTMENT ON Daum=Dnumber) JOIN EMPLOYEE ON Mgr_ssn=Ssn) WHERE Plocation='Stafford’; Not all SQL implementations have implemented the new syntax of joined tables.In some systems. a different syntax ‘was used to specify outer joitis by using the comparison operators +=, =+, and +=+ for left, right, and full outer join, respectively, when specifying the join condition. For example, this syntax is available in Oracle. To specify the left outer join using this syntax, we could write the query as follows: SELECT E.Lname, S.Lname FROM EMPLOYEE E, EMPLOYEE S WHERE E.Super_ssn +=S.Ssn; 1.2 Specification of Views in SOI, Sonim (CREATEVIEWview_mameas SELECTeolumn names) FROMUabie name WHERE condition sample ‘CREATE VIEW WORKS ONE AS SELECT Frame, Lame, Paame, Hours FROM EMPLOYEE, PROJECT, WORKS. ON WHERE. Sen-Eson ANDPan=Paumber > Weean nei SOL uo ew 2» Retevethe Last mme and First are ofall emplayecs who work on “Produc” SELECT Frame Lname FROM WORKS ONT WHERE Prame=ProductX’ > Aviowalvays shows uptodate Ite mandy the tpn the hase tables on which the view sdf the ew mst astomaially reflect hese changes > Itwe donot nea view any mar, we can use the DROP VIEW command DROP VIEW WORKS ONI: 12 View Implementation and View Unda 1 The problem officiel implementing a view for querng i complex Two main approaches have been suggested ‘SONILG 1 Asst Professor, Deptor SE SVT Pages MODULE -III NOTES DBMS -18C353 > Modifying the view query into a query onthe underlying base tables > Dadvaniage: inefficient for view dfinnd ia complex queries that are time-consuming to exeole ‘specially i multiple queries are appli othe view within shart pid of ine ‘The query example woul be automatically moifed tothe following query by the DEMS SELECT Paame, Lname FROM _ EMPLOYEE, PROJECT, WORKS_ON WHERE Sen-Eson ANDPon-Paumber AND Paame="ProductX': + View Materaization 2 Pryscally crete a temporary view ale when the view is fst queried Keep tha thle onthe acsumption that oer quis om thee wl Follow 2 Requires efficient srategy for automatically updating te view table when the base tables are updated, tat view table when a changes applied to one of he defining base abe Uplsting of ews i complicated an can be ambiguous Anup on view defined ona single able wthowt any aggregate functions canbe mapped to an upton the underlying base lable under ceria Comiiions > View involving joins, an update operation may be mapped 10 update operation on the underlying base relations nmap ways, Example ‘© Update the Paame attribute of ohn smith from ProductX to “Product” ‘UPDATE. WORKS. ONI SET Paame> Product” WHERE Caame="mith’ ANDFeame=oha” AND Prame= "Product? ‘This query eabe mappa in several updates the base relations o give the desi eet onthe view. ‘Two posse updates (a) and. (bot the base elation: coresponiing to above query (a) UPDATE WORKS ON ‘SET Pao= (SELECT Paumber FROM." PROJECT WHERE Paame= “Product¥") WHERE Esa IN (SELECT Son ee FROM. EMPLOYEE ‘WHER Lname~'smith? ANDF ame AND Pho= (SELECT Puumber FROM PROJECT WHERE Pname=ProductX” » UPDATE PROJECT. SER Paame="Product¥” WHERE. Paame= “Product\” > Update (a) slates jon sei to the “ProductN” PROJECT tuple in place of the “ProductX” PROJECT tuple and i the most ikely wpe > Update (0) woul aso give the desired update effect on the view, but it accomplishes this by changing the rae ofthe “Prout tuple inthe PROJECT relation to ‘Proc ‘THE THREE-TIER APPLICATION ARCHITECTURE Tn this section, we discuss the overall architecture of dat-inensive Internet applications. Data incesive Tteract applications can he derstood in teams of thre diferent funcional components data management, application logic, and presentation. The component tht handles data namagement ‘sual uiizes a DBMS fr dia storage, but application loi ad presentation involve mach more that justhe DBMS ise ‘Single Tihs section, we provide some perspective onthe treet architecture by discussing single Wit and cen server architectures, he predecessors ofthe thee aechiectre nial. dat itesive pplicauons were combined into single ar, tcluding the DBMS, aplication logic. al user intertace, {illustrated in Figure 75. The application typically ran ona mainrame. and users accessed it though dumb terminals that could perform only data input and display, This approach as He Benefit of being asl maintained by a cea administrator Singlestiee architectures HiWe"a important dawback: Users expect graphical interfaces that require much more computational power thin simple dum terminals. Cearalized computation of the fripical displays of sch interfaces requires much more computational power than single server Bas valle. and thus singlet architectures do scale wo thousands of use “The commoditization of the PC and the availabilty of cheap cliet computes led 10 the development ofthe two irartecture. "Twort ainectire, often ab refered to a chet-srver architectures, const of a ellent computer and a server compute. which imeract though a wel defined protocol What pat of the functionaiy the cient implement, and what prt Heft to the server, can ary. In the’ atonal sliemserver acitetre, the client implements jst the graphical wer ifrfacs, amd the server. Jniplement bah the busibes logic ad the data management such cls are ofea calle thin chen an this ercitectre lust n Figure 7 ‘SUNIL GT, Asst Professor, Deptof SESVIT. MODULE -III NOTES DBMS -18C$53. (ner divisions are posible, such 2 more powell cents hat implement bth user itrace and ‘sins logic. or clients that implement vse interface and pat ofthe business logic, with the remaining ‘art being implemented at heserver level: suc cies are te called thick cies and his architecture — DNA se | —_ . <] ‘The ticket model has several disadvantages whe Gompured to dE nctiew model. Fs, there sno central place to update ae maintain the busines logic since te application code runs a ay lien sites Second. large ammant of tant i roied between the sore and the lint. A thd “nadvantage ofthe thick clot achtectre that doesnot acale with he mamberof elles ply ‘cannot handle more than few hundred hens, ‘Thc Tie Architectures ‘The ihincienl jouer achscctre estetally separates presemalon issues from the ret of the application. The thre ier architecture goes one sep further, and also Separates application loge fom ta management / mmm ff | nin ppms || Network | Logic \ } Client Figure 78 A Standard Three-Tier Architecture SUNIL L, Asst Professor, Dept of CSE, SVIT. Page 39 MODULE -III NOTES DBMS =18CS53 Different technologies have been developed to enable distribution of the three tiers of an application across multiple hardware platforms and different physical sites. Figure 7.9 shows the technologies relevant to each ter "The three-tier architecture has the following advantages: Heterogeneous Systems: Applications can utilize the strengths of different platforms and diferent software components at the different tiers: It is easy to modify or replace the code at any tier without affecting the other ters. 2) Thin Clients: Clients only need enough computation power for the presentation layer. Typically, clients are Web browsers. 3)Integrated Data Access: In many applications, the data must be accessed from several sources. This ‘can be handled transparently at the middle tier, where we can centrally manage connections to all database systems involved. 4) Scalability to Many Clients: Each client is lightweight and all access to the system is through the ‘middle tier. The middle tier can share database connections across cients, and if the middle tier ‘becomes the bottle-neck, we can deploy several servers executing the middle tier code; clients can ‘connect to anyone of these servers, if the logic is designed appropriately. This is illustrated in Figure 7.10 Application | Logic /L* ire Network +} 1 Nenwort { oes rt } a] oT | DBMs Logic Figure 7.10 Middle Tier Replication and Access to Multiple Data Sources SQLI 'SQLI (short for ‘SQL-Java’) was developed by the SQLI Group, a group of database vendors and Sun, SQLI was developed to complement the dynamic way of creating queries in JDBC with a static ‘model. It is therefore very close to Embedded SQL. Unlike JDBC, having semi-static SQL queries allows the compiler to perform SQL syntax checks. strong type checks of the compatibility of the host variables with the respective SQL attributes, and consistency of the query with the database schema-tables, attributes, views, and stored procedures~all at compilation time. For example, in both SQLI and Embedded SQL, variables in the host language always are bound statically to the same arguments, ‘whereas in JDBC, we need separate statements to bind each variable to an argument and to retrieve the SUNIL G L, Asst Professor, Dept of CSE,SVIT. Page 29 MODULE -III NOTES DBMS -18CS53 result. For example, the following SQLI statement binds host language variables title, price, and author to the return values of the cursor books. ‘sql books = { SELECT title, price INTO stitl,:price FROM Books WHERE author = :author i‘ In JDBC, we can dynamically decide which host language variables will hold the query result, In the following example, we read the title of the book into variable fitle if the book was written by Feynman, and into variable otitle otherwise: assume we have a ResultSet cursor rs author = rs getString(3); if (author—"Feynman") ( Rite = rsgetString®2): ) ce { otile = rs.getStringt2); } When writing SQLS applications, we just write regular Java code and embed SQL statements according to ‘set of rules. SQLJ applications are pre-processed through an SQLJ translation program that replaces the embedded SQLI code with calls to an SQLI Java library. The modified program code can then be compiled by any Java compiler. Usually the SQUJ Java library makes calls to a JDBC driver, which hhandles the connection to the database system. Writine SOL Cade We will introduce SQLI by means of examples, Let us start with an SQLI code fragment that selects records from the Books table that match a given author String title; Float price; String atithor; #sql iterator Books (String title, Float price); Books books; // the application sets the author // execute the query and open the cursor #sql books = { SELECT title, price INTO :title, :price FROM Books WHERE author = :author M // retrieve results while (books.next()) { System.out.printIn(books.titleO +”, " + books.price()); } books.close() ; Driversin JDBC are classified into four types depending on the architectural relationship between the jon and the data source: « Type I Bridges: This type of driver translates JDBC function calls into function calls of another API that is not native to the DBMS. An example is a JDBC-ODBC bridge; an application can use JDBC calls to access an ODBC compliant data source. The application loads only one driver, the bridge. Bridges have the advantage that it is easy to piggy- back the applica.tion onto an existing installation, and no new drivers have to be installed, But using bridges has several drawbacks, The increased number of layers between data source and application affects performance. In addition, the user is limited to the functionality that the ODBC driver supports. = Type Il Direct Translation to the Native API via Non-Java Driver: This type of driver translates JDBC function calls directly into method invocations of the API of one specific data source. The driver is — SUNIL GL, Asst-Professor, Dept of CSE,SVIT. Page 23, MODULE -III NOTES DBMS 218CS53 usually written using a combination of C++ and Java; it is dynamically linked and specific to the data source. This architecture performs signif- icantly better than a JOBC-ODBC bridge. One disadvantage is that the database driver that implements the API needs to be installed on each computer that runs the application. = Type III--Network Bridges: The driver talks over a network to a middleware server that translates the JDBC requests into DBMS-specific method invocations. In this case, the driver on the client site (Le. the network bridge) is not DBMS-specific, The JDBC driver loaded by the ap- plication can be quite small, as the only functionality it needs to implement is sending of SQL statements to the middleware server. The middleware server can then use a Type II JDBC driver to connect to the data source. = Type IV-Direct Translation to the Native API via Java Driver: Instead of calling the DBMS API directly, the driver communicates with the DBMS through Java sockets. In this case, the driver on the client side is written in Java, but it is DBMS-specific. It translates JDBC calls into the native API of the database system. This solution does not require an in- termediate layer, and since the implementation is all Java, its performance is usually quite good. JDBC CLASSES AND INTERFACES JDBC is a collection of Java classes and interfaces that enables database access from programs ‘written in the Java language. It contains methods for connecting to a remote data source, executing SQL statements, examining ses of results from SQL statements, tansaction management, and exception handling. The classes and interfaces are part of the java.sql package. Thus. all code fragments in the remainder of this section should include the statement import java. sl * atthe beginning of the code; While JDBC provides a complete dynamic SQL interface from Java to relational databases, SQLJ fills a complementary role for static SQL. Although you can use static SQL statements in your JDBC programs, they can be represented more conveniently in SQLJ. What is the difference between SQLJ and JDBC? a With SQLJ, the owner of the application grants EXECUTE authority on the plan or package, and the recipient of that GRANT must run the application as written. With JDBC, the owner of the application grants privileges on all the underlying tables that are used by the application. Cursors ‘A tnajr problem in embedng SQL statements in hes language ike is that an impedance mismatch oxcurs because SQL operates on set of records, whersis languages like C do not ccanly suppor a sevorecords abstraction. The solution it essenlly provide a mechanism tht allows Us 1 reteve os one ata tine froma felation This mechanism i called cursor. ‘We ean declare a cursor om sty ration or on ay SQL query (becae every query returns st of rows), Once a cursor is declared, we can open it Gwhich postions the cursor jst hefore the fist ow) feach the nex sow: move the cursor (othe next row, 4 the Yow afer the extn Othe Ft rOW, oF 1 he previous row. et, by specifying additional parameters forthe FETCH command). or close the cus. ‘Thuis a cursor essctally allows us to retrieve the rows ina fable by positioning te cursor ata particular row and eading ts contents Base Cursor Definition and Usage ‘cursors enable ws o examin. inthe hos language program collction of rows compu by an Embedded SOL statement ‘We usualy nod to open a curs the embedded statement i SELECT query. However, we «can avoid opening a curse if the answer contains a single tow. INSERT, DELETE, and UPDATE statements typically require no cursor, although some variants of DELETE and UPDATE we cursor. ‘Asan example, we can ind the name and age o sailor, specified by assigning a value tothe host variable id declared earlier, sfllows: EXEC SOL ‘SELECTS sname, Sage INTO :<_smame,<_age FROM Sailor S WHERES sid = sid, ‘The INTO clause allows us to assign te columns ofthe single answer row to the ost variables «-sname and c_age. Therefore, we do nt nod curscetocemibed this query in hox language program, SUNIL GL, Asst Professor, DeptofSE,SVIT- Page 20 MODULE -III NOTES DBMS -18CS53. Bt what about the fllowing query. which computes the naa eater than the current vale ofthe host variable mineting? SELECT S.snane, Sage FROM Sailor § (WHERE Srating>:c_mineating This query returns a collection of rows, not just one row. “When executed interactively, the answers are printed on the screen. If we embed this query in 2. program by prefixing the cOlnmand with EXEC SQL. how can the answers be bound to host language variables? The INTO clause is inadequate because ‘we must deal with several rows, The solution is to use a cursor: and ages of all sabes with «rating DECLARE sinfo CURSOR FOR SELECT S.sname, Sage FROM Sailors S WHERE S.rating > 2<_minrating; This code can be included in a C program, and once it i executed, the cursor sinfo is defined, Subsequently, we can open the cursor: (OPEN info: The value of c.minrating in the SQL query associated with the cursor is the Value of this variable when we open the cursor. (The cursor declaration is processed at compile-time, and the OPEN command is executed at run-time.) A cursor canbe thought of as olan’ to A row in the collection of amwers 19 the query sociated with it. When cursor is opened. itis positioned just before the fist row, We can use the FETCH cima to read the fis row of cursor sinfo im hos langage variables FETCH sinfolNTO : name, «age ‘When the FETCH statements execute, the cursor is positioned to pot atthe next sow (which 1s the Fs row in the table when FETCH is executed forthe fist ine afer opening the cursor) and the column values im the row are copied into the corresponding hot variables. By repeatedly executing this FETCH statement (ay, in while-loop in the C program), we can read ll the ows computed by the «query, one row at «ime. Aditioal parameters to the FETCH command allow usw position a curso in tery flexible ways. How do we know When. welive looked at all he rows associated withthe cursor? By ooking at the special variables SQLCODE or SQLSTATE. of course. SQLSTATE. for example is st to the value 12000, which denotes NO DATA, to indicate tht there are no more row ithe FETCH ssterent Psion the cursor afte the last row: ‘When we are done with cursor, we can close it: CLOSE sint: ican be cpened again if nededand the value of mint the cursor would be the valve of the owt variable c-msrai inthe SQL query associates with ha tee MODULE -Ill NOTES: DBMS -18CS53, Properties of Cursors The general form of a cursor declaration is: DECLARE cursorname [INSENSITIVE] [SCROLL] CURSOR [WITH HOLD) FOR some query [ORDER BY order-item-list ] [POR READ ONLY | FOR UPDATE ] A cursor cam be declared to be a read-only cursor (FOR READ ONLY) or, if it is a cursor on a base relation or an updatable view, to be an updatable cursor (FOR UPDATE) If it is Ipdatable, simple variants of the UPDATE and DELETE commands allow us to update or delete the row 6 which the cursor is positioned. If the keyword SCROLL is specified, the cursor is scrollable, which means that variants of the FETCH command can be tused to position the cursor in very flexible ways;If the keyword INSENSITIVE is specified, the cursor behaves as if it is ranging over a private copy of the collection of answer rows.A holdable cursor is specified using the WITH HOLD clause, and is not closed when the transaction is conunitted Finally, in what order do FETCH commands retrieve rows? In general this order is unspecified, but the optional ORDER BY clause can be used to specify a sort order. Note that columns mentioned in the ORDER BY clause cannot be updated through the cursor! Sr. No. Key Database Access Efficiency Compilation Application Plan Use Cases Dynamic Statements Flexibility Static SQL In Static SQL, database access procedure is predetermined in the statement. Static SQL statements are more faster and efficient Static SQL statements are compiled at compile time. Application Plan parsing, validation, optimization and generation are compile time activities. Static SQL is used in case of uniformly distributed data Statements like EXECUTE IMMEDIATE, EXECUTE, PREPARE are not used. Static SQL is less flexible. Dynamic SQL In Dynamic SQL, how a database will be accessed, can be determine only at run time. Dynamic SQL statements are less efficient Dynamic SQL statements are compiled at run time. Application Plan parsing, validation, optimization and generation are run time activities Dynamic SQL is used in case of non-uniformly distributed data. Statements like EXECUTE IMMEDIATE, EXECUTE, PREPARE are used Dynamic SQL is highly flexible. 5.2.1 Specifving General Constraints as Assertions in SOL ASSERTIONS Th SQLwusers can specify general constraints—those that do not fall into any of the categories described via declarative assertions, using the CREATE ASSERTION statement of the DDL. Each assertion is given a constraint name and is specified via a condition similar to the WHERE clause of an SQL query. For example, to specify the constraint that the salary of an employee must not be greater than the salary of the manager of the department that the employee works fori SQL, we can write the following assertion: CREATE ASSERTION SALARY_CONSTRAINT CHECK (NOTEXISTS (SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE —E-Salary>MSalary AND E.Dno=0.Dnumber AND DMgr_ssn=MSsn ) ): The constraint name SALARY_CONSTRAINT is followed by the keyword CHECK, which is followed by a condition in parentheses that must hold true on every data- base state for the assertion to be satisfied. The constraint name can be used later to refer to the constraint or to modify or drop it. The DBMS is responsible for ensur- ing that the condition is not violated. Any WHERE clause condition can be used, but many constraints can be specified using the EXISTS and NOT EXISTS style of SQL conditions. Whenever some tuples in the database cause the condition of an ASSERTION statement to evaluate to FALSE, the constraint is violated. The con- straint is satisfied by a database state if no combination of tuples in that database state violates the constraint. The basic technique for writing such assertions is to specify a query that selects any tuples that violate the desired condition. By including this query inside a NOT EXISTSclause, the assertion will specify that the result of this query must be empty so that the condition will always be TRUE.Thus,the assertion is violated if the result of the query is not empty.In the preceding example,the query selects all employees whose salaries are greater than the salary of the ‘manager of their department. If the result of the query is not empty,the assertion is violated. $22 Intraoston to Triggers in SOL, ‘Aoater important semen im SQL is CREATE TRIGGER. In many cases itis convenient to specify he type of ‘ston Be taken whe cea vers occ an when certin conditions are ated Fr example tye tefl {o spcify a condition that if woe, causes some wer to be infrned ofthe lation The CREATE TRIGGER Snement is wed 1 implement soch actions in SQL ‘Atypial igas has three components: ee SUNIL, Ast Profesor, Dept of CSE, SVIT. Page10 MODULE -III NOTES DBMS -18CS53 + Condition optonall The conditions t,he Wager xcs thaws PPS 1 Aetion: The actions performed by the wig > ‘Theactionis tobe executed automatically ithe condition satisfied whenevent occurs & Triezer Evens Three event types pares Update + ete Two wigering times 2 MBctone the event Afr the event ‘Teo granulrites 2 Excete fr cach ow 1 ewe for each stement SUNILG Asst Profesor Deptof GSE SVIT Pager MODULE -III NOTES DBMS -18 6.5 STORED PROCEDURES: Tis often important to execute some parts of the aplication logic directly inthe process space of the database system. Running application logic directly atthe database has the advantage that the amount ‘of data that is transferred between the database server and the cleat issuing the SQL statement can be ‘minimized, while atthe same time utilizing the full power ofthe databa.se server. ‘When SQL statements are issued from a remote application, the records inthe result of the query need to he transferred from the database system back to the application. If we use a cursor to remotely access the results of an SQL statement, the DBMS has resources such as locks and memory tied up while the application is processing the records retrieved through the cursor. Incontrast, a stored procedure is a program that is executed throdgh a singlé SQL statement that ‘can be locally executed and completed within the process space of the database server. The results can be packaged into one big result and returned to the application, o the application logic can be performed ‘recy a the server, without having to transmit the results tothe elient at all, ‘Once a stored procedure is registered with the database server, diffeent users can re-use the Sored procedure, eliminating duplication of efforts in writing SQL queries or application logic, and making code maintenance ea."TY. In addition, application programmers do not meed to know the the ‘database schema if we encapsulate all databa"3e access into stored procedures. ‘Although theyare called stored procedures, they do not have to be procedures ina programming language sense: they ean be functions. 6.5.1 Creating a Simple Stored Procedure [Let us look at the example stored procedure written in SQL shown in Figure (iS. vVe see that stored Procedures must have a name; this stored procedurchas the name ‘ShowNumberOfOrders.’ Otherwise. i Just contains an SQL statement tha is precompiled and stored atthe serve, CREATE PROCEDURE ShowNumberOfOrders SELECT C.cid, C.cname, COUNT(*) FROM Customers C, Orders @ WHERE C.cid = O.cid GROUP BY C.cid, C.cname Figure 68 A Stored Procedure in SQL Stored procedures can also have parameters. These parameters have to be valid SQL types, and have one of three different modes: IN, OUT. or INOUT. IN parameters are arguments to' the stored procedure, OUT parameters are returned from the stored procedure; it assigns values to all OUT parameters that the user can process. INOUT parameters combine the properties of IN and OUT parameters: They contain values to be passed to the stored procedures, and the stored procedure can set their values as return values, Stored procedures enforce strict type conformance: If a parameter is of type INTEGER, it cannot bbe called with an argument of type VARCHAR. Let us look at an example of a stored procedure with ansuments. The stored procedure shown in Figure 69 has two arguments: book isbn and addedQty. It updates the available numberof copes of a book with the quantity from new shipment. SUNIL G L, Asst Professor, Dept of CSE,SVIT. Page 32 MODULE -III NOTES DBMS. =18CS53, CREATE PROCEDURE Addinventory ( IN book isbn CHARGO), IN addedQty INTEGER) UPDATE Rooks SET qty_in_stock = qtyjn_stock + addedgty WHERE beokjsba = isba ‘Stored procedures do not have to be written in SQL; they can be written im any host language. AS an ‘example, the stor procedure shown in Figure 6.10 is «Java function that s dynamically executed by the ‘database server whenever its called by the cient: (CREATE PROCEDURE RalllCustomers(IN number INTEGER) LANGUAGE Ja EXTERNAL NAME file: /c-/storedProcedures‘rank jar" Figure 6.10 A Stored Procedure in Java “The Common Gateway Inerface connects HTML forms with application programs. I is @ protocol that defines how arguments from forms ae passed to programs atthe server side. Programs that communicate with the webserver via CGI are often called CGX seripts, since many such application programs were written ina scripting language such lke PerlAs an example of a program that interfaces with an HTML form via CGI, consider the sample page shown in Figure 7.14. This webpage contains a form where a user can ill in the name of an author. f the user presses the ‘Seni button, the Peel script “VindBooks gi’ shown in Figure 7.14 i executed as a separate process. The CG! protocol defines how the communization between the form and the scripts performed. SUNILG L, Asst-Professor, Dept of CSE, SVIT. Page 44 MODULE -III NOTES DBMS =18CS53 Fire 7.15 illastates the processes created when using the CaLifeacol —_ ' - We Bowe "25 wesc | ee A Slee — cot Banca 2 * ‘Figure 715 Proce Seacece mith Seige Figure 7.16 shows the example CGI Sript, written in Peel, We omit errorchecking code for simplicity. Perlis an imerpreted language that is often used for CGI seripting and many Peel libraries, called modules, provide high-level interfaces to the CG! protocol. We use one such library called the DBI library, in our example. The @GI module is a convenient collection of functions for creating CGI scripts In part | of the sample script, we extract the argument of the HTML form that is passed along from the client as follows: Sauthor'Name = Sdataln- >paramCauthorName’); #l/use/bia/pert ‘use CGI; see part 1 ‘Sdatain = new COI; Sdatalar header) sathorSam ataln-t param(‘authorName’); #08 part 2 print (IGTML>CITILE Argument passing testTITLE>I) ; print (The user passed the following argument): print (iauthorName: *, Savthorame); ree part 5 print (CHTM>’), exit; igure 7116 4 Simple Pe Serpe, ‘HXML Forms HTML fonns are a common way of coma general format ofa form is the following:
A single HTML document can contain more than one form. Inside an HTML form, we can have any HTML tags except another FORM elewent. “The FORM tag has three important atibutes: s)ACTION: Specifies the URI of the page to which the form contents are submitted; ifthe ACTION attribute is absent, then the URI ofthe current page is used. b)METHOD: The HTTP/1.0 method used to submit the user input from the filled-out form to the webserver. There are two choices, GET and POST ‘© NAME: Ths atibute gives the form a name. Although not necessary, naming fotms is good style nicaling data from the client ter to the middle tier, The Inside HTML", the INPUT, SELECT, and TEXTAREA tags arc used to specify user input elements; form can have any Gents ofeach type. The simplest usr input element te an INPUT field a standalone tag with no rninating ig, An example of an INPUT ta iste following: ‘The INPUT tage several abies. The three moat important ones are TYPE, NAME, and VALUE. ‘The TYPE sitibute determines the type ofthe input Fel the TYPE atte as valu text, then the field isa ext ipa field. Ifthe TYPE attribute has vakc password, then the input ld isa test eld where the entered characters are displayed a tars on the scren. If the TYPE atbute has valve reset, it 4s simple button that reset al inp elds within the form to thee default values. 1f he TYPE ateibte tas value submit, then is butlon that sends the values ofthe differen iaputilds in the fra wo the server, Note tha reset and submit input field fet the entire form, “The NAME abut of the INPUT tag specifies the symbolic name for his ld and is used 19 ‘emi the value ofthis iput field whet is sett othe server. ‘The VALUE atihute of an inp tagcat be use fr text or password feds to speci the default contents ofthe field. For submit or reset butons, VALUE determines the label ofthe button "The foe in Figure 71 sho wo tet Feds, one regular text input eld and one password fel 1 also consis two bilons, a tesct button labeled React Values’ and a submit button labeled "Log on ‘Nae thatthe two inp ek are named, whereas the rset and submit button have no NAME atts. “" username” VALUE=" Joe">

‘SUNIL GL, Asst Professor, Deptof CSE SVIT. Page at MODULE -III NOTES DBMS -18CS; “

Figure 7.11 HTML Form with Two Test Fields and Two Buttons Passing Arguments to Server Side Seripts There are two different ways to submit HTML Form data to the webserver. Ifthe method GET is used, then the contents ofthe form are assembled into a query URI (as discussed nex!) and seat tothe serve. If the method POST is used, then the contents of the form are encoded as in the GET method, but the contents are sent ina separate data block instead of appending them directly wo ube URI. Thus, in the GET ‘method the form contents are directly visible to the user asthe constructed URL whereas in the POST method, the form contents are sent inside the HTTP request message body and are ot visible to the user. ‘Let us look atthe encoding of the URI when the GET method is used. The encode! URI has the following JavaScripts a scripting language atthe client tier th which we can add programs to-welpages that run direcily at the client (Le. at the machine cunning the Web browser). JavaScript is often used! for the following types of computation atthe cle {)Browser Detection: JavaScript can be used to detect the browser type and load a browser-specific page. 2}Form Validation: JavaScript is used to perform simple consistency checks on form fields. For example, 2 JavaScript program might check whether aform input that asks for an email/address contains the character ‘@,' or ial required flelds have been input by the user. 3} Browser Control: This includes opening pages in customized windows; examples include the annoying Pop-up advertisements that you See at many websites, which are programmed using JavaScript. Serviets Java seflets are pieces of Java code that run on the middle tier, in either webservers or application servers. There are special conventions on how to read the input from the user request and how to write output generated by the servlet. Servlets are truly platform-independent, and so they have become very popular with Web developers. Since servlets are Java programs, they are very versatile. For example, servlets can build webpages, access databases, and maintain state. Servlets have accessto all Java APIs, including JDBC. All servlets must implement the Servlet interface. In most cases, serviets extend the specific HttpServlet class for servers that communicate with clients via HTTP. The HupServlet class provides methods such as doGet and doPost to receive arguments from HTML forms, and it sends its output back to the elient via HTTP. Servlets that communicate through other protocols (such as fip) need to extend the class GenerieServlet. ‘Servlets are compiled Java classes executed and maintained by a servlet container. The servlet container manages the lifespan of individual servlets by creating and destroying them. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by webservers. For such applications, there is a useful library of HTTP-specific servlet classes. Servlets usually handle requests from HTML forms and maintain state between the client and the server.A template of a generic servlet structure is shown in Figure 7.18. This simple servlet just outputs the two words "Hello World,” but it shows the general structure of a full-fledged servlet. The request object is used to read HTML form data. The response object is used to specify the HTTP response status ————— SUNIL G L, Asst. Professor, Dept of CSE,SVIT. Page 46 MODULE -III NOTES DBMS -18CS53 code and headers of the HTTP response. The object out is used to compose the content that is returned to the client. import javaio.*; import javax servlet *; import javax servlet http.*; pUblic class ServletTemplate extends HitpServiet ( public void doGet(HttpServletRequest request, HitpServietResponse response) throws ServietException, IOException ( PrintWriter out = response getWriter(), // Use ‘out’ to send content to browser out printin("Hello World”); Figure 718 Servlet Template Application Servers Application logic can be enforced through server-side programs that are invoked using the CGI protocol. However, since each page request results in the creation of a new process, this solution does not scale well to a large number of simultaneous requests. This performance problem led to the development ofspecialized programs called application Servers. An application server maintains a pool of threads or processes and uses these to execute requests. Thus, it avoids the startup cost of creating a new process for each request. A possible architecture for a website with an application server is shown in Figure 7.17. The client (a Web browser) interacts with the webserver through the HTTP protocol. The webserver delivers static HTML or XML pages directly to the client. To assemble dynamic pages, the webserver sends a request to the application server. The application server contacts one or more data sources to retrieve necessary data or sends update requests to the data sources. After the interaction with the data sources is completed, the application server assembles the webpage and reports the result to the webserver, which retrieves the page and delivers it to the client. ‘Web Browser

You might also like