Database Application Development Chapter 6 Some

Published  . 0 views
↓ Download
Database Application Development Chapter 6 Some
1 / 1
Database Application Development Chapter 6 Some - slide 1 of 75 Database Application Development Chapter 6 Some - slide 2 of 75 Database Application Development Chapter 6 Some - slide 3 of 75 Database Application Development Chapter 6 Some - slide 4 of 75 Database Application Development Chapter 6 Some - slide 5 of 75 Database Application Development Chapter 6 Some - slide 6 of 75 Database Application Development Chapter 6 Some - slide 7 of 75 Database Application Development Chapter 6 Some - slide 8 of 75 Database Application Development Chapter 6 Some - slide 9 of 75 Database Application Development Chapter 6 Some - slide 10 of 75 Database Application Development Chapter 6 Some - slide 11 of 75 Database Application Development Chapter 6 Some - slide 12 of 75 Database Application Development Chapter 6 Some - slide 13 of 75 Database Application Development Chapter 6 Some - slide 14 of 75 Database Application Development Chapter 6 Some - slide 15 of 75 Database Application Development Chapter 6 Some - slide 16 of 75 Database Application Development Chapter 6 Some - slide 17 of 75 Database Application Development Chapter 6 Some - slide 18 of 75 Database Application Development Chapter 6 Some - slide 19 of 75 Database Application Development Chapter 6 Some - slide 20 of 75 Database Application Development Chapter 6 Some - slide 21 of 75 Database Application Development Chapter 6 Some - slide 22 of 75 Database Application Development Chapter 6 Some - slide 23 of 75 Database Application Development Chapter 6 Some - slide 24 of 75 Database Application Development Chapter 6 Some - slide 25 of 75 Database Application Development Chapter 6 Some - slide 26 of 75 Database Application Development Chapter 6 Some - slide 27 of 75 Database Application Development Chapter 6 Some - slide 28 of 75 Database Application Development Chapter 6 Some - slide 29 of 75 Database Application Development Chapter 6 Some - slide 30 of 75 Database Application Development Chapter 6 Some - slide 31 of 75 Database Application Development Chapter 6 Some - slide 32 of 75 Database Application Development Chapter 6 Some - slide 33 of 75 Database Application Development Chapter 6 Some - slide 34 of 75 Database Application Development Chapter 6 Some - slide 35 of 75 Database Application Development Chapter 6 Some - slide 36 of 75 Database Application Development Chapter 6 Some - slide 37 of 75 Database Application Development Chapter 6 Some - slide 38 of 75 Database Application Development Chapter 6 Some - slide 39 of 75 Database Application Development Chapter 6 Some - slide 40 of 75 Database Application Development Chapter 6 Some - slide 41 of 75 Database Application Development Chapter 6 Some - slide 42 of 75 Database Application Development Chapter 6 Some - slide 43 of 75 Database Application Development Chapter 6 Some - slide 44 of 75 Database Application Development Chapter 6 Some - slide 45 of 75 Database Application Development Chapter 6 Some - slide 46 of 75 Database Application Development Chapter 6 Some - slide 47 of 75 Database Application Development Chapter 6 Some - slide 48 of 75 Database Application Development Chapter 6 Some - slide 49 of 75 Database Application Development Chapter 6 Some - slide 50 of 75 Database Application Development Chapter 6 Some - slide 51 of 75 Database Application Development Chapter 6 Some - slide 52 of 75 Database Application Development Chapter 6 Some - slide 53 of 75 Database Application Development Chapter 6 Some - slide 54 of 75 Database Application Development Chapter 6 Some - slide 55 of 75 Database Application Development Chapter 6 Some - slide 56 of 75 Database Application Development Chapter 6 Some - slide 57 of 75 Database Application Development Chapter 6 Some - slide 58 of 75 Database Application Development Chapter 6 Some - slide 59 of 75 Database Application Development Chapter 6 Some - slide 60 of 75 Database Application Development Chapter 6 Some - slide 61 of 75 Database Application Development Chapter 6 Some - slide 62 of 75 Database Application Development Chapter 6 Some - slide 63 of 75 Database Application Development Chapter 6 Some - slide 64 of 75 Database Application Development Chapter 6 Some - slide 65 of 75 Database Application Development Chapter 6 Some - slide 66 of 75 Database Application Development Chapter 6 Some - slide 67 of 75 Database Application Development Chapter 6 Some - slide 68 of 75 Database Application Development Chapter 6 Some - slide 69 of 75 Database Application Development Chapter 6 Some - slide 70 of 75 Database Application Development Chapter 6 Some - slide 71 of 75 Database Application Development Chapter 6 Some - slide 72 of 75 Database Application Development Chapter 6 Some - slide 73 of 75 Database Application Development Chapter 6 Some - slide 74 of 75 Database Application Development Chapter 6 Some - slide 75 of 75
Description: Database Application Development Chapter 6 Some useful links http:msdn.microsoft.comen-uslibrarytw738475.aspx http:www.w3schools.comadodefault.asp http:www.w3schools.comphpdefault.asp Overview Concepts covered in this lecture:

Related Topics

Download Presentation

"Database Application Development Chapter 6 Some" is the property of its rightful owner. Permission is granted to download and print the materials on this website for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.

Presentation Transcript

slide1. Database Application Development Chapter 6<br>
slide2. Some useful links http://msdn.microsoft.com/en-us/library/tw738475.aspx
http://www.w3schools.com/ado/default.asp
http://www.w3schools.com/php/default.asp<br>
slide3. Overview Concepts covered in this lecture:
SQL in application code
Embedded SQL
Cursors
Dynamic SQL
JDBC
SQLJ
Stored procedures<br>
slide4. Content Introduction and Cursor
Embedded SQL
JDBC
SQLJ
Stored Procedures
SQL/PSM<br>
slide5. Programming Models Four Types:
SQL on console
Embedded SQL
Driver based (e.g. JDBC, ODBC)
Stored Procedures (standard: SQL/PSM)<br>
slide6. SQL Programming models Console Embedded SQL in C Driver Based Application CREATE PROCEDURE IncreaseRating( IN sailor_sid INTEGER, IN increase INTEGER)
UPDATE Sailors
…… Stored Procedures<br>
slide7. SQL in Application Code SQL commands can be called from within a host language (e.g., C++ or Java) program.
SQL statements can refer to host variables (including special variables used to return status).
Must include a statement to connect to the right database.
Two main integration approaches:
Embed SQL in the host language (Embedded SQL, SQLJ)  This is getting obselete.
Create special API to call SQL commands (JDBC)<br>
slide8. Impedance Mismatch and Cursor SQL relations are (multi-) sets of records, with no a priori bound on the number of records.
No such data structure exist traditionally in procedural programming languages such as C++.
This mismatch with SQL is called impedance mismatch
SQL supports a mechanism called a cursor to handle this.
Cursor: A control structure to allows traversal through multiple records.<br>
slide9. Content Introduction and Cursor
Embedded SQL
JDBC
SQLJ
Stored Procedures
SQL/PSM<br>
slide10. Embedded SQL Approach: Embed SQL in the host language.
A preprocessor converts the SQL statements into special API calls.
The preprocessor is DBMS-dependent. Each DBMS has its own pre-processor.
Then a regular compiler is used to compile the code.
Executable works with a particular DBMS for which the code was compiled.

Language constructs:
Declare host variables: EXEC SQL BEGIN (END) DECLARE SECTION
Connect to a database: EXEC SQL CONNECT
Execute query Statements: EXEC SQL Statement;
May need to open a CURSOR<br>
slide11. Embedding SQL in C: An Example char SQLSTATE[6];
EXEC SQL BEGIN DECLARE SECTION
char c_sname[20]; short c_minrating; float c_age;
EXEC SQL END DECLARE SECTION
EXEC SQL CONNECT TO {[server_name.]database_name} [AS connection_name] USER [login[.password] | $integrated]
c_minrating = random();
EXEC SQL DECLARE sinfo CURSOR FOR
SELECT S.sname, S.age FROM Sailors S
WHERE S.rating > :c_minrating
ORDER BY S.sname;
EXEC SQL OPEN sinfo;
do {
EXEC SQL FETCH sinfo INTO :c_sname, :c_age;
printf(“%s is %d years old\n”, c_sname, c_age);
} while (SQLSTATE != ‘02000’); // while FOUND
EXEC SQL CLOSE sinfo; Declare Variables Declare and Open a cursor Execute the query and traverse results Connect to DB<br>
slide12. Dynamic SQL Allows construction of SQL statements on-the-fly

Example:
char c_sqlstring[]= {“DELETE FROM Sailors WHERE raiting>5”};
EXEC SQL PREPARE readytogo FROM :c_sqlstring;
EXEC SQL EXECUTE readytogo;<br>
slide13. Embedded SQL – overall program structure Include required SQL environment files (use #include <sqlenv.h> and #include <sqlutil.h>
Declare Variables within host program (use EXEC SQL BEGIN/ END DECLARE)
Include SQLCA for error codes (use EXEC INCLUDE SQLCA)
Connect to database (use EXEC SSQL CONNECT)
Declare Cursor for multiple reads (use EXEC SQL DECLARE cursor_name CURSOR FOR sql_query)
Interact with database:
Read data from cursor (either copied or pointed by cursor) (use EXEC SQL FETCH cursor_name INTO :local_variable1, :local_variable2;)
Update data in DB (use EXEC SQL UPDATE…)
Read one row (use EXECX SQL SELECT..WHERE sid = some)
For dynamic query (use EXEC SQL PREPARE stmt_dyn FROM :str_stmt; and then EXEC SQL EXECUTE stmt_dyn FROM :input_var)
Close connection (use EXEC SQL CLOSE cursor_name)
Log off from database and free all resources (use EXEC SQL COMMIT RELEASE)<br>
slide14. Content Introduction and Cursor
Embedded SQL
JDBC
SQLJ
Stored Procedures
SQL/PSM<br>
slide15. Database APIs: Alternative to embedding Rather than modify compiler, add library with database calls (API)
Special standardized interface: procedures/objects
Pass SQL strings from language, presents result sets in a language-friendly way
At the high level, two key options: Sun’s JDBC: Java API and Microsoft’s ODBC
a “driver” traps the calls and translates them into DBMS-specific code
database can be across a network<br>
slide16. Good References For ODBC: www.microsoft.com/data/odbc
For JDBC: java.sun.com/products/jdbc
Books: “ODBC developer’s guide” by Sanders, “JDBC DB access with Java…” by Hamilton Extra Info<br>
slide17. Driver-based (e.g. JDBC) Architecture Four architectural components:
Application (initiates and terminates connections, submits SQL statements)
Driver manager (load JDBC driver)
Driver:
connects to data source,
transmits requests and
returns/translates results and error codes)
Data source (processes SQL statements)<br>
slide18. JDBC Classes and Interfaces JDBC is a collection of Java classes and interfaces that enables database access from programs written in Java.
It contains methods for:
Connecting to a data source
Executing SQL statements
Examining sets of results from SQL queries
Transaction management
Exception handling
Java application should include the java.sql package:
import java.sql.*<br>
slide19. Steps to connect to the database Load the JDBC driver
Connect to the data source
Execute SQL statements (use ResultSet)<br>
slide20. STEP 1: Loading the JDBC driver - JDBC Driver Management All drivers are managed by the Drivermanager class, which has methods to dynamically add/delete drivers
Loading a JDBC driver:
In the Java code: Class.forName(“oracle/jdbc.driver.Oracledriver”);
(for SQL server) Driver d = (Driver)Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
This will automatically register the driver
Alternatively, when starting the Java application include on the command line: -Djdbc.drivers=oracle/jdbc.driver<br>
slide21. STEP 2: Connections in JDBC We interact with a data source through sessions. Each connection identifies a logical session.
Connections are specified through a JDBC URL, a URL that uses the jdbc protocol: jdbc:<subprotocol>:<otherParameters>

Example:
String url=“jdbc:oracle:www.bookstore.com:3083”;
Connection con;
try{
con = DriverManager.getConnection(url,userId,password);
}
catch (SQLException excpt) { …}<br>
slide22. More on JDBC URL - example jdbc:oracle:<drivertype>:@<hostname>:<port>:<database_sid>
<drivertype> - can be either "thin" or "oci" (thick) [oci - Oracle Call Interface, version of oci can also be appended , oci8 - Oracle 8 DB version]
<hostname> - The machine name where the database is running (IP address can also be used).
<port> - The port number where the database listener is running
<database_sid> - The database SID of database
Example : jdbc:oracle:thin:@10.185.13.158:1521:ora9i
here 10.185.13.158 - The IP address of machine where db is running
1521 - Port where db listener is running
ora9i - The Database SID FYI only<br>
slide23. Connection Class Interface public int getTransactionIsolation() and void setTransactionIsolation(int level) Sets isolation level for the current connection. Manages how changes are visible to other concurrent transactions
public boolean getReadOnly() and void setReadOnly(boolean b) Specifies whether transactions in this connection are read-only
public boolean getAutoCommit() and void setAutoCommit(boolean b) If autocommit is set, then each SQL statement is considered its own transaction. Otherwise, a transaction is committed using commit(), or aborted using rollback().
public boolean isClosed() Checks whether connection is still open. FYI only<br>
slide24. STEP 3: Executing SQL Statements Three different ways of executing SQL statements:
Statement (both static and dynamic SQL statements)
PreparedStatement (dynamic SQL statements)
CallableStatment (stored procedures)

Statement is the base class for the other two statement classes.<br>
slide25. PreparedStatement Class Dynamically generates pre-complied SQL code
Can have parameters but structure is fixed
Values of parameters are determined at run-time<br>
slide26. Show example here See handout on driver based code<br>
slide27. Example: Executing Prepared SQL Statements String sql=“INSERT INTO Sailors VALUES(?,?,?,?)”;
PreparedStatment pstmt=con.prepareStatement(sql);
pstmt.clearParameters();
pstmt.setInt(1,sid);
pstmt.setString(2,sname);
pstmt.setInt(3, rating);
pstmt.setFloat(4,age);

// There are different ways for submitting the query string to the data source
// If we know that no rows are returned, we can use executeUpdate()
int numRows = pstmt.executeUpdate(); Preparing statement Executing statement<br>
slide28. ExecuteQuery & ResultSets PreparedStatement.executeUpdate only returns the number of affected records
PreparedStatement.executeQuery returns data, encapsulated in a ResultSet object (a cursor)

Statement pstmt = NULL;
Pstmt = con.createStatement();
ResultSet rs=pstmt.executeQuery(sql);
// rs is now a cursor
While (rs.next()) {
// process the data
} Declaring cursor in java Executing query returning multiple rows Process cursor content<br>
slide29. Callable Statement JDBC:
CallableStatement cstmt= con.prepareCall(“{call ShowSailors});
ResultSet rs = cstmt.executeQuery();
while (rs.next()) {

} For calling Stored procedures<br>
slide30. ResultSets (Contd.) A ResultSet is a very powerful cursor:
previous(): moves one row back
absolute(int num): moves to the row with the specified number
relative (int num): moves forward or backward
first() and last()<br>
slide31. Matching Java and SQL Data Types These (accessor) methods are used to retrieve values from the current row of the query result referenced by the ResultSet object.
There are two forms for each method: by column index or by column name. Briefly<br>
slide32. JDBC: Exceptions and Warnings Similar to SQLSTATE in embedded SQL. For error handling.
Most of java.sql can throw an SQLException if an error occurs.
It supports the following methods:
getMessage( )
getSQLState( )
getNextException( )
SQLWarning is a subclass of SQLException; not as severe (they are not thrown and their existence has to be explicitly tested)
Connection, statement, and resultSet objects all have a getWarnings( ) FYI only<br>
slide33. Warning and Exceptions (Contd.) try {
stmt=con.createStatement();
warning=con.getWarnings();
while(warning != null) {
// handle SQLWarnings;
warning = warning.getNextWarning():
}
con.clearWarnings();
stmt.executeUpdate(queryString);
warning = stmt.getWarnings();

} //end try
catch( SQLException SQLe) {
// handle the exception
} FYI only<br>
slide34. Examining Database Metadata DatabaseMetaData object gives information about the database system and the catalog.

DatabaseMetaData md = con.getMetaData();
// print information about the driver:
System.out.println( “Name:” + md.getDriverName() + “version: ” + md.getDriverVersion());
Metadata has 134 methods!<br>
slide35. Database Metadata (Contd.) DatabaseMetaData md=con.getMetaData();
ResultSet trs=md.getTables(null,null,null,null);
String tableName;
While(trs.next()) {
tableName = trs.getString(“TABLE_NAME”);
System.out.println(“Table: “ + tableName);
//print all attributes
//iterating on columns not rows
ResultSet crs = md.getColumns(null,null,tableName, null);
while (crs.next()) {
System.out.println(crs.getString(“COLUMN_NAME” + “, “);
}
} SKIP<br>
slide36. A (Semi-)Complete Example //Load driver
Connection con = // connect
DriverManager.getConnection(url, ”login", ”pass");
Statement stmt = con.createStatement(); // set up stmt
String query = "SELECT name, rating FROM Sailors";
ResultSet rs = stmt.executeQuery(query);
try { // handle exceptions
// loop through result tuples
while (rs.next()) {
String s = rs.getString(“name"); //gets the value for the string in column “name”
Int n = rs.getIntrating");
System.out.println(s + " " + n);
}
} catch(SQLException ex) {
System.out.println(ex.getMessage ()
+ ex.getSQLState () + ex.getErrorCode ());
}<br>
slide37. Content Introduction and Cursor
Embedded SQL
JDBC
SQLJ
Stored Procedures
SQL/PSM<br>
slide38. SQLJ Complements JDBC with a (semi-)static query model
Compiler can perform syntax checks, strong type checks, consistency of the query with the schema
All arguments always bound to the same variable: #sql mybooks = { SELECT name, rating INTO :name, :rating FROM Books WHERE sid = :sid;
Compare to JDBC (note getString(2) can be bound to diff variables.) sid=rs.getInt(1); if (sid==1) {sname=rs.getString(2);} else { sname2=rs.getString(2);}
SQLJ (part of the SQL standard) versus embedded SQL (vendor-specific)<br>
slide39. SQLJ Iterator (cursor) Example Code Int sid; String name; Int rating;
// named iterator
#sql iterator Sailors(Int sid, String name, Int rating); //Declare iterator class
Sailors sailors; //Instantiate Iterator
// assume that the application sets rating
//Initialize iterator
#sql sailors = {
SELECT sid, sname INTO :sid, :name FROM Sailors WHERE rating = :rating
};
// retrieve results. Iteratively read from the iterator rows
while (sailors.next()) {
System.out.println(sailors.sid + “ “ + sailors.sname));
}
sailors.close(); //close iterator<br>
slide40. SQLJ Iterators Two types of iterators (“cursors”):
Named iterator
Need both variable type and name, and then allows retrieval of columns by name.
See example on previous slide.
Positional iterator
Need only variable type, and then uses FETCH .. INTO construct: #sql iterator Sailors(Int, String, Int); Sailors sailors; #sailors = … while (true) { #sql {FETCH :sailors INTO :sid, :name, :rating} ; if (sailors.endFetch()) { break; } // process the sailor } Note similarity to embedded SQL<br>
slide41. Content Introduction and Cursor
Embedded SQL
JDBC
SQLJ
Stored Procedures
SQL/PSM<br>
slide42. Stored Procedures What is a stored procedure:
Program executed through a single SQL statement
Executed in the process space of the server
Advantages:
Can encapsulate application logic while staying “close” to the data
Reuse of application logic by different users
Avoid tuple-at-a-time return of records through cursors<br>
slide43. NOTE on Syntax! That Syntax for Stored Procedures has differences for different DBMS.
The following slides are based on textbook and external references (applicable mostly with MySQL).
The goal is to give you multiple flavors, while emphasizing the capability of Stored Procedures.
Syntax specific to the lab (SQL server) will be covered in the Lab.<br>
slide44. Stored Procedures: Examples CREATE PROCEDURE ShowNumReservations SELECT S.sid, S.sname, COUNT(*) FROM Sailors S, Reserves R WHERE S.sid = R.sid GROUP BY S.sid, S.sname

Stored procedures can have parameters:
Three different modes: IN, OUT, INOUT

CREATE PROCEDURE IncreaseRating( IN sailor_sid INTEGER, IN increase INTEGER)
UPDATE Sailors
SET rating = rating + increase WHERE sid = sailor_sid<br>
slide45. Calling Stored Procedures Interactive
CALL storedProcedure (arguments…)
Using embedded SQL:
EXEC SQL BEGIN DECLARE SECTION
Int sid;
Int rating;
EXEC SQL END DECLARE SECTION

// now increase the rating of this sailor
EXEC CALL IncreaseRating(:sid,:rating);<br>
slide46. Calling Stored Procedures (Contd.) JDBC:
CallableStatement cstmt= con.prepareCall(“{call ShowSailors});
ResultSet rs = cstmt.executeQuery();
while (rs.next()) {

} SQLJ:
#sql iterator ShowSailors(…);
ShowSailors showsailors;
#sql showsailors={CALL ShowSailors};
while (showsailors.next()) {

}<br>
slide47. Content Introduction and Cursor
Embedded SQL
JDBC
SQLJ
Stored Procedures
SQL/PSM<br>
slide48. SQL/PSM (Persistent Stored Modules) Most DBMSs allow users to write stored procedures in a simple, general-purpose language (close to SQL)  SQL/PSM standard is a representative

Declare a stored procedure:
CREATE PROCEDURE name(p1, p2, …, pn)
local variable declarations
procedure code;
Declare a function:
CREATE FUNCTION name (p1, …, pn) RETURNS sqlDataType local variable declarations
function code;<br>
slide49. Main SQL/PSM Constructs CREATE FUNCTION rate Sailor (IN sailorId INTEGER) RETURNS INTEGER //Return values
DECLARE rating INTEGER // Declare variables
DECLARE numRes INTEGER
SET numRes = (SELECT COUNT(*) //Assign variables
FROM Reserves R WHERE R.sid = sailorId)
IF (numRes > 10) THEN rating =1; //IF-THEN branch
ELSE rating = 0;
END IF;
RETURN rating; //Return values<br>
slide50. Main SQL/PSM Constructs (Contd.) Local variables (DECLARE)
RETURN values for FUNCTION
Assign variables with SET
Branches and loops:
IF (condition) THEN statements; ELSEIF (condition) statements; … ELSE statements; END IF;
LOOP statements; END LOOP
Queries can be parts of expressions
Can use cursors naturally without “EXEC SQL”<br>
slide51. Summary Embedded SQL allows execution of parametrized static queries within a host language
Dynamic SQL allows execution of completely ad-hoc queries within a host language
Cursor mechanism allows retrieval of one record at a time and bridges impedance mismatch between host language and SQL
APIs such as JDBC introduce a layer of abstraction between application and DBMS<br>
slide52. Summary (Contd.) SQLJ: Static model, queries checked a compile-time.
Stored procedures execute application logic directly at the server
SQL/PSM standard for writing stored procedures<br>
slide53. Backup<br>
slide54. Content Introduction and Cursor
Embedded SQL
JDBC
SQLJ
Stored Procedures
SQL/PSM<br>
slide55. Embedded SQL Approach: Embed SQL in the host language.
A preprocessor converts the SQL statements into special API calls.
The preprocessor is DBMS-dependent. Each DBMS has its own pre-processor.
Then a regular compiler is used to compile the code.

Language constructs:
Declare host variables: EXEC SQL BEGIN (END) DECLARE SECTION
Connect to a database: EXEC SQL CONNECT
Execute query Statements: EXEC SQL Statement;
May need to open a CURSOR<br>
slide56. EXEC SQL CONNECT EXEC SQL CONNECT;
 
 
SQL server syntax:
EXEC SQL CONNECT TO {[server_name.]database_name} [AS connection_name] USER [login[.password] | $integrated]

Reference: http://msdn.microsoft.com/en-us/library/aa225245(SQL.80).aspx<br>
slide57. Embedded SQL: Variables Host variables must be declared as follows:
EXEC SQL BEGIN DECLARE SECTION
char c_sname[20];
long c_sid;
short c_rating;
float c_age;
EXEC SQL END DECLARE SECTION

Such host variables must be prefixed a column (:) in SQL statements.
SQL defines the standard for matching types of variables between SQL and host language. E.g. c_sid has the type INTEGER in SQL<br>
slide58. Embedded SQL: Exceptions Error codes are made available through including the following data structure (SQLCA = SQL Communication Area)
EXEC SQL INCLUDE SQLCA;
Two special “error” variables which are part of the sqlca data structure can be used to check for errors
sqlca.sqlcode (long, is negative if an error has occurred)
sqlca.sqlstate (char[6], predefined codes for common errors)
Can use the condition SQL statement to check for errors:
EXEC SQL WHENEVER [SQLERROR | NOT FOUND] [CONTINUE | GOTO statement]<br>
slide59. Cursors Can declare a cursor on a relation or query statement (which generates a relation).
Can open a cursor, and repeatedly fetch a tuple then move the cursor, until all tuples have been retrieved.
Can use a special clause, called ORDER BY, in queries that are accessed through a cursor, to control the order in which tuples are returned.
Fields in ORDER BY clause must also appear in SELECT clause.
The ORDER BY clause, which orders answer tuples, is only allowed in the context of a cursor.
Can also modify/delete tuple pointed to by a cursor.<br>
slide60. Cursor that gets names of sailors who’ve reserved a red boat, in alphabetical order Note that it is illegal to replace S.sname by, say, S.sid in the ORDER BY clause! (Why?) EXEC SQL DECLARE sinfo CURSOR FOR
SELECT S.sname
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’
ORDER BY S.sname<br>
slide61. General form for cursor DECLARE cursor_name [INSENSITIVE] [SCROLL] CURSOR FOR {select_stmt | prepared_stmt_name} [FOR { READ ONLY | UPDATE [ OF column_list ] } ]<br>
slide62. Embedding SQL in C: An Example char SQLSTATE[6];
EXEC SQL BEGIN DECLARE SECTION
char c_sname[20]; short c_minrating; float c_age;
EXEC SQL END DECLARE SECTION
EXEC SQL CONNECT TO {[server_name.]database_name} [AS connection_name] USER [login[.password] | $integrated]
c_minrating = random();
EXEC SQL DECLARE sinfo CURSOR FOR
SELECT S.sname, S.age FROM Sailors S
WHERE S.rating > :c_minrating
ORDER BY S.sname;
EXEC SQL OPEN sinfo;
do {
EXEC SQL FETCH sinfo INTO :c_sname, :c_age;
printf(“%s is %d years old\n”, c_sname, c_age);
} while (SQLSTATE != ‘02000’); //NOT FOUND
EXEC SQL CLOSE sinfo; Declare Variables Open a cursor Execute the query and traverse results Connect to DB<br>
slide63. Dynamic SQL SQL query strings are now always known at compile time (e.g., spreadsheet, graphical DBMS frontend): Allow construction of SQL statements on-the-fly

Example:
char c_sqlstring[]= {“DELETE FROM Sailors WHERE raiting>5”};
EXEC SQL PREPARE readytogo FROM :c_sqlstring;
EXEC SQL EXECUTE readytogo;<br>
slide64. Embedded SQL references http://infolab.stanford.edu/~ullman/fcdb/oracle/or-proc.html
http://download.oracle.com/docs/cd/A57673_01/DOC/api/doc/PAD18/apb.htm
Include files reference: http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp?topic=/com.ibm.db2.luw.apdv.embed.doc/doc/r0005905.html<br>
slide65. Summary – Embedded SQL (see handout for illustration) Include required SQL environment files (use #include <sqlenv.h> and #include <sqlutil.h>
Declare Variables within host program (use EXEC SQL BEGIN/ END DECLARE)
Include SQLCA for error codes (use EXEC INCLUDE SQLCA)
Connect to database (use EXEC SSQL CONNECT)
Declare Cursor for multiple reads (use EXEC SQL DECLARE cursor_name CURSOR FOR sql_query)
Interact with database:
Read data from cursor (either copied or pointed by cursor) (use EXEC SQL FETCH cursor_name INTO :local_variable1, :local_variable2;)
Update data in DB (use EXEC SQL UPDATE…)
Read one row (use EXECX SQL SELECT..WHERE sid = some)
For dynamic query (use EXEC SQL PREPARE stmt_dyn FROM :str_stmt; and then EXEC SQL EXECUTE stmt_dyn FROM :input_var)
Close connection (use EXEC SQL CLOSE cursor_name)
Log off from database and free all resources (use EXEC SQL COMMIT RELEASE)<br>
slide66. Compatibility of Embedded SQL executable DBMS specific pre-processor transforms the embedded SQL statements into function calls in the host language.
Translation is dependent on DBMS
Source code can be compiled with different DBMS
Executable works with a particular DBMS for which the code was compiled.<br>
slide67. Example: IBM DB2 development options Use DB2 APIs to perform administrative functions such as backing up and restoring databases.
Embed static and dynamic SQL statements in your applications programmed in C, C++, COBOL, FORTRAN, and REXX™.
Code DB2 Call Level Interface ( DB2 CLI) function calls in your applications to invoke dynamic SQL statements.
Develop Java™ applications and applets using the Java Database Connectivity application programming interface (JDBC API) or embedded SQL for Java (SQLJ).
Develop Microsoft® Visual Basic and Visual C++ applications using ActiveX Data Object (ADO).
Develop ADO.NET applications using IBM® Data Server Provider for .NET ( DB2 .NET), OLE DB .NET Data Provider or ODBC .NET Data Provider.
Develop applications using IBM or third-party tools such as Excel, Perl, and Open Database Connectivity (ODBC) end-user tools such as Lotus® Approach®, and its programming language, LotusScript.
Develop web applications using PHP scripting language and Ruby on Rails (RoR) which is a framework for developing web applications that access databases.
Develop web applications using Python, which is a general purpose, high-level scripting language that is well-suited for rapid application development. Extra Info<br>
slide68. ODBC - Microsoft “Open Database Connectivity (ODBC) is Microsoft's strategic interface for accessing data in a heterogeneous environment of relational and non- relational database management systems. Based on the Call Level Interface specification of the SQL Access Group, ODBC provides an open, vendor- neutral way of accessing data stored in a variety of proprietary personal computer, minicomputer, and mainframe databases.” Extra Info<br>
slide69. Steps to use ODBC To use ODBC, the following three components are required: ODBC CLIENT - an ODBC-enabled front-end (also called ODBC client) - Examples: Microsoft Access, an application created with Access, an application created with Microsoft Visual Basic, an application created with C+Win SDK+ODBC SDK, or ODBC-enabled applications from other vendors (such as Lotus). ODBC DRIVER - an ODBC Driver for the ODBC Server. The ODBC Driver Catalog contains an extensive listing of ODBC Drivers. For example, the Microsoft ODBC Driver Pack is a collection of seven ODBC Drivers ready to be used or bundled with ODBC clients. A SQL Server ODBC Driver is included with Access, and Informix is working on an ODBC driver for Informix.
Any ODBC client can access any DBMS for which there is an ODBC Driver. DBMS SERVER is a back-end or server DBMS, for example SQL Server, Oracle, AS/400, Foxpro, Microsoft Access, or any DBMS for which an ODBC driver exists. Extra Info<br>
slide70. JDBC - SUN The Java Database Connectivity (JDBC) API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases – SQL databases and other tabular data sources, such as spreadsheets or flat files. The JDBC API provides a call-level API for SQL-based database access.
JDBC technology allows you to use the Java programming language to exploit "Write Once, Run Anywhere" capabilities for applications that require access to enterprise data. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment. Extra Info<br>
slide71. Example – connecting to mysql DB #include <libmysqlwrapped.h>
int main()
{ Database db("localhost", "root", "", "tutorialdb");
if (!db.Connected())
{ printf("Database not connected - exiting\n");
exit(-1);
}
}<br>
slide72. Error handling with embedded SQL You can connect C/C++ labels with SQL as in:    
EXEC SQL WHENEVER SQLERROR GOTO error_in_SQL;    
/* ... */
error_in_SQL:     /* do error handling */<br>
slide73. JDBC Architecture (Contd.) Four types of drivers:
Bridge:
Translates SQL commands into non-native API. Example: JDBC-ODBC bridge. Code for ODBC and JDBC driver needs to be available on each client.
Direct translation to native API, non-Java driver:
Translates SQL commands to native API of data source. Need OS-specific binary on each client. Fast.
Network bridge:
Send commands over the network to a middleware server that talks to the data source. Needs only small JDBC driver at each client.
Direction translation to native API via Java driver:
Converts JDBC calls directly to network protocol used by DBMS. Needs DBMS-specific Java driver at each client.<br>
slide74. JDBC connection Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");

This step is also simple, with the hardest thing being what to supply for url . If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: . The rest of the URL is generally your data source name or database system. So, if you are using ODBC to access an ODBC data source called " Fred, " for example, your JDBC URL could be jdbc:odbc:Fred . In place of " myLogin " you put the name you use to log in to the DBMS; in place of " myPassword " you put your password for the DBMS. So if you log in to your DBMS with a login name of " Fernanda " and a password of " J8, " just these two lines of code will establish a connection:
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

If you are using a JDBC driver developed by a third party, the documentation will tell you what subprotocol to use, that is, what to put after jdbc: in the JDBC URL. For example, if the driver developer has registered the name acme as the subprotocol, the first and second parts of the JDBC URL will be jdbc:acme: . The driver documentation will also give you guidelines for the rest of the JDBC URL. This last part of the JDBC URL supplies information for identifying the data source.<br>
slide75. Connecting to SQL Server http://support.microsoft.com/kb/265808<br>