1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Database Systems: The Complete Book- P5 pptx

50 1,4K 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 4,54 MB

Nội dung

3 76 CHAPTER 8. SYSTEM ASPECTS OF SQL 1) CREATE FUNCTION GetYear (t VARCHAR(255) ) RETURNS INTEGER 2) DECLARE Not-Found CONDITION FOR SQLSTATE '02000'; 3) DECLARE Too-Many CONDITION FOR SQLSTATE '21000'; BEGIN 4) DECLARE EXIT HANDLER FOR Not-Found, Too-Many 5) RETURN NULL ; 6) RETURN (SELECT year FROM Movie WHERE title = t); END ; Figure 8.14: Handling exceptions in which a single-row select returns other than one tuple Line (6) is the statement that does the work of the function GetYear. It is a SELECT statement that is expected to return exactly one integer, since that is what the function GetYear returns. If there is exactly one movie with title t (the input parameter of the function), then this value will be returned. However. if an exception is raised at line (6), either because there is no movie with title t or several movies with that title, then the handler is invoked, and NULL instead becomes the return-value. Also, since the handler is an EXIT handler, control next passes to the point after the END. Since that point is the end of the funrtion. GetYear returns at that time, with the return-value NULL. 0 8.2.8 Using PSM Functions and Procedures As we mentioned in Section 8.2.2, we can call a PSM function or procedtire from a program with embedded SQL, from PSLI code itself, or from ordinary SQL commands issued to the generic interface. The use of these procedures and functions is the same as in most programming languages, with procedures invoked by CALL, and functions appearing as past of an expression. Ke shall give one example of how a function can be called from the generic interface. Example 8.16 : Suppose that our schema includes a module with the functio!i Getyear of Fig. 8.14. Imagine that we are sitting at the generic interface. and we want to enter the fact that Denzel Washington was a star of Remember the Titans. However. we forget the year in which that movie was made. AS long as there was only one movie of that name. and it is in the Movie relation. 15-e don't have to look it up in a preliminary query. Rather, we can issue to the generic SQL interface the following insertion: 8.2. PROCEDURES STORED IN THE SCHEAIA 377 Since GetYear returns NULL if there is not a unique movie by the name of Remember the Titans, it is possible that this insertion will have NULL in the middle component. 0 8.2.9 Exercises for Section 8.2 Exercise 8.2.1 : Using our running movie database: Movie(title, year, length, incolor, studiolame, producerC#) StarsIn(movieTitle, movieyear, starName) MovieStar(name, address, gender, birthdate) MovieExec(name, address, cert#, networth) Studio(name, address, presC#) write PSM procedures or functions to perform the following tasks: * a) Given the name of a movie studio, produce the net worth of its president. * b) Given a name and address, return 1 if the person is a movie star but not an executive, 2 if the person is an executive but not a star, 3 if both, and 4 if neither. *! c) Given a studio name. assign to output parameters the titles of the two longest movies by that studio. Assign NULL to one or both parameters if there is no such movie (e.g., if there is only one mo~ie by a studio, there is no 'Lsecond-longest'i ) . ! d) Given a star name, find the earliest (lowest year) movie of more than 120 minutes length in u-hich they appeared. If there is no such movie, return the year 0. e) Given an address. find the name of the unique star with that address if there is exactly one, and return NULL if there is none or more than one. f) Given the name of a star, delete them from Moviestar and delete all their movies from StarsIn and Movie. Exercise 8.2.2: Write the following PSlI functions or procedures, based on . the database schema Product (maker, model, type) PC(mode1, speed, ram, hd, rd, price) Laptop(mode1, speed, ram, hd, screen, price) Printer(mode1, color, type, price) of Exercise 5.2.1. INSERT INTO StarsIn(movieTitle, movieyear, starName) VALUES( 'Remember the Titans', Getyear( 'Remember the Titans ' 1, * a) Take a price as argument and return the model number of the PC whose 'Denzel Washington'); price is closest. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 378 CH.4PTER 8. SYSTEM ASPECTS OF SQL b) Take a maker and model as arguments, and return the price of whatever type of product that model is. ! c) Take model, speed, ram, hard-disk, removable-disk, and price information as arguments, and insert this information into the relation PC. Ifowever, if there is already a PC with that model number (tell by assuming that violation of a key constraint on insertion will raise an exception with SQLSTATE equal to '23000'), then keep adding 1 to the model number until you find a model number that is not already a PC model number. ! d) Given a price, produce the number of PC's, the number of laptops, and the number of printers selling for more than that price. Exercise 8.2.3 : Write the following PSM functions or procedures, based on the database schema Classes(class, type, country, numGuns, bore, displacement) Ships(name, class, launched) Battles(name, date) Outcomes(ship, battle, result) of Exercise 5.2.4. a) The firepower of a ship is roughly proportional to the number of guns times the cube of the bore. Given a class, find its firepower. ! b) Given the name of a battle, produce the two countries whose ships viere involved in the battle. If there are more or fewer than two countrie. involved, produce NULL for both countries. c) Take as arguments a new class name, type, country, number of guns, bore. and displacement. Add this information to Classes and also add the ship with the class name to Ships. 8.3. THE SQL ENVIRONAIEiYT 8.3 The SQL Environment In this section we shall take the broadest possible view of a DBMS and the databases and programs it supports. We shall see how databases are defined and organized into clusters, catalogs, and schemas. \Ye shall also see how programs are linked with the data they need to manipulate. Many of the details depend on the particular implementation, so we shall concentrate on the general ideas that are contained in the SQL standard. Sections 8.4 and 8.5 illustrate how these high-level concepts appear in a "call-level interface,' which requires the programmer to make explicit connections to databases. 8.3.1 Environments An SQL environment is the framework under which data may exist and SQL operations on data may be executed. In practice, we should think of an SQL environment as a DBMS running at some installation. For example, ABC company buys a license for the Megatron 2002 DBMS to run on a collection of XBC's machines. The system running on these machines constitutes an SQL environment. All the database elements we have discussed - tables, views, triggers, stored procedures, and so on - are defined within an SQL environment. These ele- ments are organized into a hierarchy of structures, each of which plays a distinct role in the organization. The structures defined by the SQL standard are incli- cated in Fig. 8.15. Briefly, the organization consists of the following structures: 1. schema^.^ These are collections of tables, views. assertions, triggers. PSlI modules, and some other types of information that \ye do not discuss in this book (but see the box on "More Schema Elements" in Section 8.3.2). Schemas are the basic units of organization, close to what we might think of as a "database." but in fact somewhat less than a database as we shall see in point (3) below. ! d) Given a ship name, determine if the ship was in a battle with a date before the ship was launched. If so, set the date of the battle and the date the 2. Cataloos. These are collections of schemas. They are the basic unit for ship was launched to 0. supporting unique, accessible terminolog?l. Each catalog has one or more schemas; the names of schemas within a catalog must be unique. and ! Exercise 8.2.4: In Fig. 8.12, we used a tricky formula for computillg the each catalog contains a special schema called INFORMATIONSCHEMA that variance of a sequence of numbers XI, x2, . . . , xn. Recall that the variance is contains information about all the schemas in the catalog. the average square of the deviation of these numbers from their mean. That is. the variance is xi - 2)') In, where the mean I is (Cr=, xi)/*. Prow 3. Clu.sters. These are collections of catalogs. Each user has an associated that the formula for the variance used in Fig. 8.12, which is cluster: the set of all catalogs accessible to the user (see Section 8.7 for an explanation of how access to catalogs and other elements is controlled). (k(xi)2)/n - ((exi,/n)2 SQL is not very precise about what a cluster is. e.g., whether clusters i= 1 for various users can overlap without being identical. .& cluster is the i=l yields the same value. 3~ote that the term "schema" in this context refers to a database schema, not a relation Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 8. SYSTEM ASPECTS OF SQL n Environment = Cluster = of a DB operation Figure 8.15: Organization of database elements within the environment maximum scope over which a query can be issued, so in a sense, a cluster is "the database" as seen by a particular user. 8.3. THE SQL ENVIROhiSIENT CREATE SCHEMA MovieSchema CREATE TABLE Moviestar . . . as in Fig. 7.5 Create-table statements for the four other tables CREATE VIEW Movieprod . . . as in Example 6.48 Other view declarations CREATE ASSERTION RichPres . . . as in Example 7.13 Figure 8.16: Declaring a schema It is not necessary to declare the schema all at once. One can modify or add to a schema using the appropriate CREATE, DROP, or ALTER statement, e.g., CREATE TABLE followed by the declaration of a new table for the schema. One problem is that the SQL system needs to know in which schema the new table belongs. If we alter or drop a table or other schema element, we may also need to disambiguate the name of the element, since two or more schemas may have distinct elements of the same name. We change the "current" schema with a SET SCHEMA statement. For exam- ple, SET SCHEMA MovieSchema; makes the schema described in Fig. 8.16 the current schema. Then, any decla- rations of schema elements are added to that schema, and any DROP or ALTER statements refer to elements already in that schema. 8.3.2 Schemas 8.3.3 Catalogs The simplest form of schema declaration consists of: 1. The keywords CREATE SCHEMA. 2. The name of the schema. 3. A list of declarations for schema elements such as base tables, views, and assert ions. That is, a schema may be declared by: CREATE SCHEMA <schema name> <element declarations> Just as schema elements like tables are created within a schema, schemas are created and modified within a catalog. In principle, we would expect the process 4 of creating and populating catalogs to be analogous to the process of creating i and populating schemas. Unfortunately, SQL does not define a standard way :'. to do so. such as a statement 4. pj CREATE CATALOG <catalog name> follolved by a list of schemas belonging to that catalog and the declarations of those schemas. Ho~vet-er. SQL does stipulate a statement The element declarations are of the forms discussed in various places, such as Sections 6.6. 6.7.1. 7.4.3, and 8.2.1. SET CATALOG <catalog name> Example 8.17: We could declare a schema that includes the fire relations about movies that we have been using in our running example, plus some of This statement alloms us to set the "current-' catalog, so new schemas will go the other elements we have introduced. such as views. Figure 8.16 sketches the into that catalog and schema modifications will refer to schemas in that catalog form of such a declaration. should there be a name ambiguity. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. More Schema Elements Some schema elements that we have not already mentioned, but that oc- casionally are useful are: Domains: These are sets of values or simple data types. They are little used today, because object-relational DBMS's provide more powerful type-creation mechanisms; see Section 9.4. Character sets: These are sets of symbols and methods for encoding them. ASCII is the best known character set, but an SQL imple- mentation may support many others, such as sets for various foreign languages. Collations: Recall from Section 6.1.3 that character strings are com- pared lexicographically, assuming that any two characters can be compared by a "less than" relation we denoted <. A collation spec- ifies which characters are "less than" which others. For example, we might use the ordering implied by the ASCII code, or we might treat lower-case and capital letters the same and not compare any- thing that isn't a letter. Grant statements: These concern who has access to schema elements. We shall discuss the granting of privileges in Section 8.7. - Complete Names for Schema Elements Formally, the name for a schema element such as a table is its catalog name, its schema name, and its own name, connected by dots in that order. Thus, the table Movie in the schema Movieschema in the catalog Moviecatalog can be referred to as MovieCatalog.MovieSchema.Movie If the catalog is the default or current catalog, then we can omit that component of the name. If the schemais also the default or current schema, then that part too can be omitted, and we are left with the element's own name, as is usual. However, we have the option to use the full name if we need to access something outside the current schema or catalog. I 382 (XlAPTER 8. SYSTEM ASPECTS OF SQL 8.3. THE SQL ENVIRONMENT 383 CONNECT TO <server name> AS <connection name> AUTHORIZATION <name and password> The server name is something that depends on the inst,allation. The word DEFAULT can substitute for a name and will connect the user to whatever SQL server the installation treats as the "default server." We have shown an au- thorization clause followed by the user's name and password. The latter is the typical method by which a user would be identified to the server, although other strings following AUTHORIZATION might be used. The con~lection name can be used to refer to the connection later on. The reason we might have to refer to the connection is that SQL allows several 8.3.4 Clients and Servers in the SQL Environment connections to be opened by the user, but only one can be active at any time. To slvitch among connections, we can make connl become the active connection An SQL environment is more than a collection of catalogs and schemas. It by the statement: contains elements whose purpose is to support operations on the database or databases represented by those catalogs and schema. Within an SQL enr7i- SET CONNECTION connl; ronment are two special kinds of processes: SQL clients and SQL servers. -4 server supports operations on the database elements, and a client allows a user IIThatewr connection was currently active becomes dormant until it is reacti- to connect to a server and operate on the database. It is envisioned that the rated xith another SET CONNECTION statement that mentions it explicitly. server runs on a large host that stores the database and the client runs on an- We also use the name when rye drop the connection. \17e can drop connection other host, perhaps a personal workstation remote from the server. However. it is also possible that both client and server run on the same host. DISCONNECT connl; Soxv, connl is terminated; it is not dormant and cannot be reactivated. 8.3.5 Connections Ho~vever, if we shall never need to refer to the connection being created, then AS and the connection name may be omitted from the CONNECT TO statement. Ewe wish to run some program involving SQL at a host where an SQL client ex- It is also permitted to skip the connection statements altogether. If we simply ists~ then we may open a connection between the client and server by executing execute SQL statements at a host with an SQL client, then a default connection an SQL statement will be established on our behalf. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 8. SYSTEM ASPECTS OF SQL SQL-client SQL-sewer Session Figure 8.17: The SQL client-server interactions 8.3.6 Sessions The SQL operations that are performed ~vliile a connection is active form a session. The session is coextensive with the connection that created it. For example, when a connection is made dormant, its session also becomes dormant. and reactivation of the connection by a SET CONNECTION statement also makes the session active. Thus, we have shown the session and connection as tn.0 aspects of the link between client and server in Fig. 8.17. Each session has a current catalog and a current schema within that catalog. These may be set with statements SET SCHEMA and SET CATALOG, as discussed in Sections 8.3.2 and 8.3.3. There is also an authorized user for every session. as we shall discuss in Section 8.7. 8.3.7 Modules -4 module is the SQL term for an application program. The SQL standard suggests that there are three kinds of modules, but insists only that an SQL implementation offer the user at least one of these types. 1. Generic SQL Interface. The user may type SQL statements that are executed by an SQL server. In this mode, each query or other statement is a module by itself. It is this mode that we imagined for most of our examples in this book, although in practice it is rarely used. 2. Embedded SQL. This style was discussed in Section 8.1, where SQL state- ments appear within host-language programs and are introduced by EXEC SQL. Presumably, a preprocessor turns the embedded SQL statements into 8.4. LiSIA7G -4 CALL-LEVEL INTERE4CE 385 suitable function or procedure calls to the SQL system. The compiled host-language program, including these function calls, is a module. 3. True Ilfodules. The most general style of modules envisioned by SQL is one in which there are a collection of stored functions or procedures, some of which are host-language code and some of which are SQL statements. They communicate among themselves by passing parameters and perhaps via shared variables. PSlI modules (Section 8.2) are an example of this type of module. An execution of a module is called an SQL agent. In Fig. 8.17 we have shown both a module and an SQL agent, as one unit, calling upon an SQL client to establish a connection. However, we should remember that the distinction between a module and an SQL agent is analogous to the distinction between a program and a process; the first is code, the second is an execution of that code. 1 8.4 Using a Call-Level Interface In this section we return to the matter of coordinating SQL operations and host-language programs. We saw embedded SQL in Section 8.1 and we covered procedures stored in the schema (Section 8.2). In this section, we take up a third approach. M-hen using a call-level interface (CLI), we write ordinary host- language code. and we use a library of functions that allow us to connect to and access a database, passing SQL statements to that database. The differences between this approach and embedded SQL programming are, in one sense, cosmetic. If we observed what the preprocessor does with embedded SQL statements, we would find that they were replaced by calls to library functions much like the functions in the standard SQLICLI. However, 11-hen SQL is passed by CLI functions directly to the database server, there is a certain level of system independence gained. That is, in principle, we could run the same host-language progranl at several sites that used different DBlIS's. -1s long as those DBlIS's accepted standard SQL (which unfortunately is not al~vays the case), then the same code could run at all these sites, without a specially designed preprocessor. \Ve shall give two esamples of call-level interfaces. In this section, we corer the standard SQLICLI. which is an adaptation of ODBC (Open Database Con- nectivit\-). In Section 8.5. we consider JDBC (Java Database Connectivity), a similar standard that links Java programs to databases in an object-oriented style. In neither case do we cover the standard exhausti\-el5 preferring to show the flavor only. 8.4.1 Introduction to SQL/CLI -1 program ~vritten in C and using SQLICLI (hereafter, just CLI) will include the header file sqlcli. h, from which it gets a large number of functions, type Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 386 CHAPTER 8. SYSTEM ASPECTS OF SQL 8.4. USING A CALL-LEVEL INTERFACE 387 definitions, structures, and symbolic constants. The program is then able to that there is no relevant value here. If you want a connection handle, create and deal with four kinds of records (structs, in C): then hIn is the handle of the environment within which the connection will exist, and if you want a statement handle, then hIn is the handle of 1. Environments. A record of this type is created by the application (client) the connection within which the statement will exist. program in preparation for one or more connections to the database server. 3. hOut is the address of the handle that is created by SQLAllocH~dle. 2. Connections. One of these records is created to connect the application program to the database. Each connection exists within some environ- SQLAllocHandle also returns a value of type SQLRETURN (an integer). This ment. value is 0 if no errors occurred, and there are certain nonzero values returned in the case of errors. 3. Statements. An application program can create one or more statement records. Each holds information about a single SQL statement, including Example 8.18 : Let us see how the function worthRanges of Fig. 8.4, which we an implied cursor if the statement is a query. At different times, the used as an example of embedded SQL, would begin in CLI. Recall this function same CLI statement can represent different SQL statements. Every CLI examines all the tuples of MovieExec and breaks their net worths into ranges. statement exists within some connection. The initial steps are shown in Fig. 8.18. 4. Descriptions. These records hold information about either tuples or pa- rameters. The application program or the database server, as appropriate, 1) #include sqlc1i.h sets components of description records to indicate the names and types of 2) SQLHENV myEnv; attributes and/or their values. Each statement has several of these created 3) SQLHDBC mycon; implicitly, and the user can create more if needed. In our presentation of 4) SQLHSTMT execstat; CLI, description records will generally be invisible. 5) SQLRETURN errorcodel, errorCode2, errorCode3; Each of these records is represented in the application program by a han- 6) errorcodel = SQLA~~OCH~~~~~(SQL-HANDLE-ENV, dle, which is a pointer to the reco~-d.4 The header file sqlcli .h provides SQL-NULL-HANDLE, &myEnv) ; types for the handles of environments, connections, statements, and descrip 7) if (! errorcodel) tions: SQLHENV, SQLHDBC, SQLHSTMT, and SQLHDESC, respectively, although Ire errorcode2 = SQLAllocHadle(SQL-HANDLE-DBC, may think of them as pointers or integers. We shall use these types and also myEnv, &mycon) ; some other defined types with obvious interpretations, such as SQL-CHAR arlti 9) if ( ! errorCode2) SQL-INTEGER, that are provided in sqlcli . h. errorcode3 = SQLAllocH~dle(SQL-HANDLE-STMT, IfTe shall not go into detail about how descriptions are set and used. Holy- mycon, &execstat); ever, (handles for) the other three types of records are created by the use of a function Figure 8.18: Declaring and creating an environment, a connection, and a st,ate- SQLAllocHandle (hnpe, hIn, h0ut) Here, the three arguments are: Lines (2) through (4) declare handles for an envimment, connection, and statement, respectively; their names are myEnv, mycon, and execstat, respec- 1. hType is the type of handle desired. Use SQLHANDLEXNV for a new en+ til-el~. \fTe plan that execstat will represent the SQL statement ronment, SQLHANDLEDBC for a new connection, or SQLHANDLESTMT for a new statement. SELECT networth FROM MovieExec; 2. hIn is the handle of the higher-level element in which the newly allocated nluch as did the cursor execcursor in Fig. 8.4, but as Yet there is no SQL element lives. This parameter is SQLaULLHANDLE if you want an envi- statement associated with execstat. Line (5) declares three variables into ronment; the latter name is a defined constant telling SQLAllocHandle which function calls can place their response and indicate an error. -4 value of 90 not confuse this use of the term "handlen with the handlers for exceptions that were 0 indicates no error occurred in the call, and we are counting on that being the discussed in Section 8.2.7. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 388 CHAPTER 8. SYSTEM ASPECTS OF SQL 8.4. USIXG A CALL-LEVEL 1-NTERFACE 389 What is in Environments and Connections? We shall not examine the contents of the records that represent environ- ments and connections. However, there may be useful information con- tained in fields of these records. This information is generally not part of the standard, and may depend on the implementation. However, as an example, the environment record is required to indicate how character strings are represented, e.g., terminated by '\O' as in C, or fixed-length. Line (6) calls SQLAllocHandle, asking for an environment handle (the first argument), providing a null handle in the second argument (because none is needed when we are requesting an environment handle), and providing the address of myEnv as the third argument; the generated handle will be placed there. If line (6) is successful, lines (7) and (8) use the environment handle to get a connection handle in mycon. Assuming that call is also successful, lines (9) and (10) get a statement handle for execstat. 8.4.2 Processing Statements At the end of Fig. 8.18, a statement record whose handle is execstat, has been created. However, there is as yet no SQL statement with ~hich that record is associated. The process of associating and executing SQL statements with statement handles is analogous to the dynamic SQL described in Section 8.1.10. There, we associated the text of an SQL statement with what we called an "SQL variable," using PREPARE, and then executed it using EXECUTE. The situation in CLI is quite analogous, if we think of the %QL variable" as a statement handle. There is a function SQLPrepare (sh, st, SO that takes: 1. -1 statement handle sh, 2. A pointer to an SQL statement st, and causes the statement to which handle sh refers to be executed. For many forms of SQL statement, such as insertions or deletions, the effect of executing this statement on the database is obvious. Less obvious is what happens when the SQL statement referred to by sh is a qnery. As we shall see in Section 8.4.3, there is an implicit cursor for this statement that is part of the statement record itself. The statement is in principle executed, so we can imagine that all the answer tuples are sitting somewhere, ready to be accessed. We can fetch tuples one at a time, using the implicit cursor, much as we did with real cursors in Sections 8.1 and 8.2. Example 8.19 : Let us continue with the function worthflanges that we began in Fig. 8.18. The following two function calls associate the query SELECT networth FROM MovieExec; with the statement referred to by handle execstat: 11) SQLPrepare(execStat, "SELECT networth FROM MovieExec", SQL-NTS) ; 12) SQLExecute(execStat) ; They could appear right after line (10) of Fig. 8.18. Remember that SQLNTS tells SQLPrepare to determine the length of the null-terminated string to which its second argument refers. .Is u-ith dynamic SQL, the prepare and execute steps can be combined into one if we use the function SQLExecDirect. -In example that combines lines (11) and (12) above is: SQLExecDirect(execStat, "SELECT networth FROM MovieExec", SqL-NTS) ; 8.4.3 Fetching Data From a Query Result The function that corresponds to a FETCH command in embedded SQL or PSM is 3. -1 length sl for the character string pointed to by st. If we don't know the f length, a defined constant SQLNTS tells SQLPrepare to figure it out from the string itself. Presumably, the string is a h'null-terminated string." and n-liere sh is a statement handle We presume the statement referred to by sh it is sufficient for SQLPrepare to scan it until encountering the endmarker '\O'. has been executed already, or the fetch \%-ill cause an error. SqLFetch, like all CLI functions, returns a value of type SQLRETURN that indicates either success The effect of this function is to arrange that the statement referred to by the or an error. We should be especially aware of the return value represented by handle sh now represents the particular SQL statement st. the symbolic constant S~LNIDATA, which indicates that no more tuples were Another function left in the query result. As in our previous examples of fetching, this value will Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 390 CHAPTER 8. SYSTEM ASPECTS OF SQL 8.4. USING A C-ALL-LEVEL IXTERFACE be used to get us out of a loop in which we repeatedly fetch new tuples from 1) #include sqlc1i.h the result. 2) void worthRanges0 However, if we follow the SQLExecute of Example 8.19 by one or more SQLFetchcalls, where does t,he t,uple appear? The answer is that its components int i, digits, counts[l51; go into one of the description records associated with the statement whose SQLHENV myEnv; handle appears in the SQLFetch call. We can extract the same component at SQLHDBC mycon; each fetch by binding the component to a host-language variable, before we SQLHSTMT execstat; begin fetching. The function that does this job is: SQLINTEGER worth, worthInfo; SQLBindCol(sh, colNo, colTgpe, pvar, varsize, varhfo) SQLAllocHandle(SQL-HANDLE-ENV, The meanings of these six arguments are: SQL-NULL-HANDLE, &rny~nv); SQLAllocHandle(SQL-HANDLE-DBC, myEnv. &mycon) ; 1. sh is the handle of the statement involved. SQLAllocHandle(SQL-HANDLE-STMT , mycon, &execstat) ; SQLPrepare(execStat, 2. colNo is the number of the component (within the tuple) whose value we "SELECT networth FROM MovieExec", SQL-NTS); obtain. SQLExecute (execstat) ; 3. colType is a code for the type of the variable into which the value of the SQLBindCol(execStat, 1, SQL-INTEGER, &worth, component is to be placed. Examples of codes provided by sqlcli. h arc sizeof (worth), &worthInf o) ; SQL-CHAR for character arrays and strings, and SQL-INTEGER for integers. while(~~~~etch(execStat) ! = SQL-NO-DATA) { digits = 1; 4. p Var is a pointer to the variable into which the value is to be placed. while((worth /= 10) > 0) digits++; if (digits <= 14) counts [digits] ++; 5. varSize is the length in bytes of the value of the variable pointed to by p Var. for(i=O; i<15; i++) 6. varInfo is a pointer to an integer that can be used by SQLBindCol to printf("digits = Id: number of execs = %d\nI1, provide additional information about the value produced. i, counts[il) ; Example 8.20: Let us redo the entire function worthRanges from Fig. 8.4. using CLI calls instead of embedded SQL. We begin as in Fig. 8.18, but for the sake of succinctness, we skip all error checking except for the test ~hether SQLFetch indicates that no more tuples are present. The code is shown in Figure 8.19: Grouping executive net ~vorths: CLI version Fig. 8.19. Line (3) declares the same local variables that the embedded-SQL version worth. The fifth argument is the size of that variable, and the final argument of the function uses, and lines (4) through (7) declare additional local variables poillts to worthInfo, a place for SQLBindCol to put additional information , using the types provided in sqlcli . h; these are variables that involve SQL in some way. Lines (4) through (6) are as in Fig. 8.18. New are the declarations (n-hich 11-e do not use here). on line (7) of worth (which corresponds to the shared variable of that name in The balance of the function resembles closely lines (11) through (19) of Fig. 8.4) and worthInfo. rshich is required by SQLBindCol, but not used. Fig. 8.1. The ~s-hile-loop begins at line (14) of Fig. 8.19. Sotice that we fetch Lines (8) through (10) allocate the needed handles, as in Fig. 8.18: and a tuple and check that we are not out of tuples, all within the condition of the lines (11) and (12) prepare and execute the SQL stat.ement, as discussed in I\-hile-loop? on line (14). If there is a tuple, then in lines (13) through (17) we Example 8.19. In line (13): we see the binding of the first (and only) colunln of determine the number of digits the integer (which is bound to worth) has and the result of this query to the variable worth. The first argument is the handle increment the appropriate count. After the loop finishes, i.e., all tuples returned for the statement in\-olved; and the second argument is the column involved: by the statement execution of line (12) have been examined, the resulting counts 1 in this case. The third argument is the type of the column, and the fourth are printed out at lines (18) and (19). argument is a pointer to the place where the value will be placed: the variable Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 392 CHAPTER 8. SYSTEM ASPECTS OF SQL Extracting Components with SQLGetData An alternative to binding a program variable to an output of a query's result relation is to fetch tuples without any binding and then trans- fer components to program variables as needed. The function to use is SQLGetData, and it takes the same arguments as SQLBindCol. However, it only copies data once, and it must be used after each fetch in order to have the same effect as initially binding the column to a variable. 8.4.4 Passing Parameters to Queries Embedded SQL gives us the ability to execute an SQL statement, part of which consists of values determined by the current contents of shared variables. There is a similar capability in CLI, but it is rather more complicated. The steps needed are: 1. Use SQLPrepare to prepare a statement in which some portions, called parameters, are replaced by a question-mark. The ith question-mark rep- resents the ith parameter. 2. Use function SqLBindParameter to bind values to the places where the question-marks are found. This function has ten arguments, of which we shall explain only the essentials. 3. Execute the query with these bindings, by calling SQLExecute. Sote that if v.e change the values of one or more parameters, we need to cal! SQLExecute again. The following example will illustrate the process, as well as indicate the impor- tant arguments needed by SQLBindParameter. Example 8.21: Let us reconsider the embedded SQL code of Fig. 8.2, where we obtained values for two variables studioName and studioAddr and used them as the components of a tuple, which we inserted into Studio. Figure 8.20 sketches how this process would work in CLI. It assumes that we have a state- ment handle mystat to use for the insertion statement. The code begins with steps (not shown) to give studioName and studioAddr values. Line (1) shows statenlent mystat being prepared to be an insertion statement with two parameters (the question-marks) in the VALUE clause. Then. lines (2) and (3) bind the first and second question-marks, to the current con- tents of studioNarne and studioAddr, respectively. Finally, line (4) executes the insertion. If the entire sequence of steps in Fig. 8.20, including the un- seen n-ork to obtain new values for studioName and studiodddr, are placed in a loop, then each time around the loop, a new tuple, with a new name and address for a studio, is inserted into Studio. /* get values for studioName and studioAddr */ 1) SQ~Prepare (mystat, "INSERT INTO Studio (name, address) VALUES(?, ?I", SQL-NTS) ; 2) SQLBindParameter(myStat, 1,. . . , studioName, . . .) ; 3) SQLBindParameter(myStat, 2, , studioAddr, 1; 4) SQLExecute (mystat) ; Figure 8.20: Inserting a new studio by binding parameters to values 8.4.5 Exercises for Section 8.4 Exercise 8.4.1 : Repeat the problems of Exercise 8.1.1, but write the code in C with CLI calls. Exercise 8.4.2 : Repeat the problems of Exercise 8.1.2, but write the code in C with CLI calls. 8.5 Java Database Connectivity JDBC, which stands for "Java Database Connectivity," is a faci1it.y similar to CLI for allowing Java programs to access SQL databases. The concepts are quite similar to those of CLI, although Java's object-oriented flavor is evident in JDBC. 8.5.1 Introduction to JDBC The first steps we must take to use JDBC are: 1. Load a "driver" for the database system we shall use. This step may be installation- and implementation-dependent. The effect, however, is that an object called DriverManager is created. This object is analogous in many lvays to the environment whose handle we get as the first step in using CLI. 2. Establish a connection to the database. .\ variable of type Connection is created if n-e apply the method getconnection to DriverManager. The Java statement to establish a connection looks like: Connection mycon = ~river~anager.getConnection(<URL>, <name>, <password>) ; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 394 CHAPTER 8. SYSTEM ASPECTS OF SQL 8.5. JL4VA DATrlBASE CONA~ECTIVITY 395 That is, the method getconnection takes as arguments the URL for the d) executeupdate(), with no argument, is applied to a Preparedstatement. database to which you wish to connect, your user name, and your passn-ord. In that case, the SQL statement associated with the prepared statement It returns an object of type Connection, which we ha\re chosen to call mycon. is executed. This SQL statement must not be a query, of course. Note that in the Java style, mycon is given its type and value in one statement. This connection is quite analogous to a CLI connection, and it serves the Example 8.22 : Suppose we have a connection object mycon, and we wish to execute the query same purpose. BY applying the appropriate methods to a connection like mycon, we can create statement objects, place SQL st,atements "in" those objects, bind SELECT networth FROM MovieExec; values to SQL statement parameters, execute the SQL statements, and examine results a tuple at a time. Since the differences between JDBC and CLI are often One way to do so is to create a statement object execstat, and then use it to more syntactic than semantic, we shall go only briefly through these steps. execute the query directly. The result set will be placed in an object Worths of type ResultSet; we'll see in Section 8.5.3 how to extract the net worths and 8.5.2 Creating Statements in JDBC process them. The Java code to accomplish this task iJ! There are two methods we can apply to a connection in order to create state- Statement execstat = myCon.createStatement0; ments. They differ in the number of their arguments: ResultSet Worths = exec~tat.executeQuery( "SELECT networth FROM MovieExec") ; 1. createstatemento returns an object of type Statement. This object has no associated SQL statement yet, so method createstatement () An alternative is to prepare the query immediately and later execute it. may be thought of as analogous to the CLI call to SQLAllocHandle that This approach would be preferable, as in the analogous CLI situation, should takes a connection handle and returns a statement handle. lve want to execute the same query repeatedly. Then, it makes sense to prepare it once and execute it many times, rather than having the DBMS prepare the 2. preparestatement (Q), where Q is an SQL query passed as a string argu- same query repeatedly. The JDBC steps needed to follow this approach are: ment, returns an object of type PreparedStatement. Thus, we may draw an analogy between executing preparestatement (Q) in JDBC with the Preparedstatement execstat = my~on.prepareStatement( two CLI steps in which we get a statement handle with SQLAllocHandle "SELECT networth FROM MovieExec") ; and then apply SQLPrepare to that handle and the query Q. ResultSet Worths = execstat. executequery 0 ; There are four different methods that execute SQL statements. Like the methods above, they differ in whether or not they take a statement as an Example 8.23 : ~f we want to execute a parameterless nonquery, we can per- argument. However, these methods also distinguish between SQL statements form analogous steps in both styles. There is no result set, however- For that are queries and other statements, which are collectively called "updates." instance, suppose n-e want to insert into StarsIn the fact that Denzel b'sh- Note that the SQL UPDATE statement is only one small example of what JDBC ington starred in Remember the Titans in the year 2000. We may create and terms an "update." The latter include all modification statements, such as use a statement starstat in either of the following lt-a~s: inserts, and all schema-related statements such as CREATE TABLE. The four "execute" methods are: Statement starstat = myCon.createStatement0; starStat.executeUpdate("INSERT INTO StarsIn VALUES(" + a) executeQuery(Q) takes a statement Q, which must be a query, and is "'Remember the TitansJ, 2000, 'Denzel Washington')"); applied to a Statement object. This method returns an object of type Resultset, which is the set (bag, to be precise) of tuples produced by the query Q. We shall see how to access these tuples in Section 8.5.3. PreparedStatement starstat = my~on.prepareStatement( b, executequer~o is applied to a Preparedstatement object. Since a pre "INSERT INTO ~tars~n VALUES('Remember the Titans'," + pared statement already has an associated query, there is no argument. 1s2000, 'Denzel Washington' 1 "1 ; This method also returns an object of type Resultset. starStat.executeUpdate0; C) executeu~date(U) takes a nonquery statement U and, when applied to Sotice that each of these sequences of Java statements takes advantage of the a statement object, executes U. The effect is felt on the databaqe only: fact that + is a Java operator that concatenates strings. Thus, are able to no result set is returned. extend SQL statements over several lines of Jwa, as needed. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... studio that oxns this movie is "Disney," then the complete object m becomes a member of the output bag The fourth line specifies that the object,s m produced by the select-from-wherequery are to be ordered first by the value of m l e n g t h (i.e., the length of the movie) and then, if there are ties, by the value of m t i t l e (i.e., the title of the movie) The value produced by this query is thus... manipulates either the database or the schema begins The SQL command START TRANSACTION may be used if we wish In the generic interface, unless started with a START TRANSACTION command, the transaction ends with the statement In all other cases, there are two ways to end a transaction: 1 The SQL statement COMMIT causes the transaction to end successfully Whatever changes to the database were caused by the SQL... to the length component of this Movie object is a result, the select-from query produces the bag of lengths of the movies in a particular group For instance, if s t d o has the value "Disney" and y r has the value 1990, then the result of the select-from is the bag of t h e lengths of the movies made by Disney in 1990 When we apply the S M operator to this bag U we get the sum of the lengths of the. .. in the (mys ) pairs that satisfy the W E E clause These names are HR the names of the stars in the set m, s t a r s , where m, is the Casablanca movie object 0 (a) An expression whose value has a collection type, e.g a set or bag (b) The optional keyn-ord AS, and (c) The name of the variable Typically the expression of (a) is the extent of some class, such as the extent Movies for class Movie in the. .. from one account to another cally: that is, either they are both done or neither is done For example, a simple solution is to have all changes to the database done in a local workspace: and only after all work is done do we commit the changes to the database, whereupon all changes become part of the database and visible to other operations 8.6.3 Transactions The solution to the problems of serialization... If so then lines (12) through (14) add the amount to the second account, and lilies (15) through (17) subtract the amount from the first account If the amount in the first account is insufficient, then no transfer is made, and a warning is printed at line (18) Sow, consider what happens if there is a failure after line (14); perhaps the computer fails or the network connecting the database to the processor... r 2 The type of each field is the class S t a r since that is the type of the variables s l and s 2 that provide values for the two fields That is formally, the type of the structure is Struct(star1: Star, star2: star) The type of the result of the query is a set of these structures, that is: Set Example 9.4 : Let us find the set of Disney movies, but let the. .. number of times a movie appears in the result of either subquery is zero or one, so the result is the same regardless of whether DISTINCT is used However, the type of the result differs If DISTINCT is used, then the type of the result is Set,while if DISTINCT is omitted in one or both places, then the result is of type Bag 9.2.6 ! c) For each gun bore, find the earliest year in which any... obtained on database elements These privileges include the right to select (read), insert: delete, or update relations, the right to reference relations (refer to them in a constraint), and the right to create triggers + Grant Diagrams: Privileges may be granted by owners to other users or to the general user PUBLIC If granted with the grant option, then these privileges may be passed on to others Privileges... the best of SQL into the object-oriented world, then the relatively new, object-relational features of the SQL-99 standard can be characterized as bringing the bcst of object-orientation into the relational xvorld In some senses, the two languages "meet in the middle." but there are differences in approach that make certain things easier in one language than the other In essence, the two approaches to . perhaps the computer fails or the network connecting the database to the processor that is actually performing the transfer fails. Then the database. on the database has been that of one user querying or modifying the database. Thus, operations on the database are executed one at a time, and the database

Ngày đăng: 21/01/2014, 18:20

Nguồn tham khảo

Tài liệu tham khảo Loại Chi tiết
1. Cattell, R. G. G. (ed.), The Object ~at'abase Standard: ODMG-99, Nor- gan-Kaufmann, San Francisco, 1999 Sách, tạp chí
Tiêu đề: The Object ~at'abase Standard: ODMG-99
1. The variable y appears in tlie head but not in any nonnegated. relational subgoal. Xotice the fact that y appears in the arithmetic subgoal x &lt; y does not help to limit the possible values of y to a finite set. .Is soon as we find values a, b. and c for w, x. and z respectively that satisfy the first two subgoals, the infinite number of tuples (b.d) such that d &gt; b wind up in the head's relation P Sách, tạp chí
Tiêu đề: x "< y does not help to limit the possible values of y to a finite set. .Is soon as we find values a, "b. "and "c "for w, x. and "z "respectively that satisfy the first two subgoals, the infinite number of tuples "(b.d) "such that "d
3. Variable y appears in an arithmetic subgoal, but not in a nonnegated, relational subgoal.Thus, it is not a safe rule and cannot be used in Datalog.There is another xi-ay to define the meaning of rules. Instead of consider- ing all of the possible assignments of values to variables, n-e consider the sets of tuples in the relations corresponding to each of the nonnegated, relational subgoals. If some assignment of tuples for each nonnegated, relational subgoal is consistent. in the sense that it assigns the same i-alue t o each occurrence of a variable. then consider the resulting assignment of values t o all the variables of the rule. Sotice that because the rule is safe. every variable is assigned a value Sách, tạp chí
Tiêu đề: consistent
10.1.3 Datalog Rules and Queries Operations similar to those of the classical relational algebra of Section 5.2 are described in Datalog by rules, which consist of Khác
3. -1 body consistil~g of one or more atoms, called subgoals, which may be either relational or arithmetic. Subgoals are connected by AND, and any subgoal may optionally be preceded by the logical operator NOT Khác

TỪ KHÓA LIÊN QUAN