Download presentation
Presentation is loading. Please wait.
1
Chap 8. SQL in a Server Environment-PartIII
2
Using a Call-Level Interface
Programming SQL with procedural languages embedded SQL (ESQL) embedded SQL statements are replaced by calls to SQL library functions stored procedure, e.g., PSM using a call-level interface (CLI) SQL/CLI, JDBC, DB library in PHP write ordinary host-language code, and use a library of functions that allow us to connect to and access a database, passing SQL statements to that database e.g., the functions in the standard SQL/CLI procedure or function stored in the schema low-level API
3
Using a Call-Level Interface (cont’d)
part of the SQL standard ODBC: released in 1992, by MS. - objective: provide an open API for accessing SQL data, which is independent of PL, OS, DBMS Introduction to SQL/CLI SQL/CLI a set of the standard SQL library functions an adaptation of ODBC(open database connectivity) header file sqlcli.h included in programs written in C and using SQL/CLI a large number of functions, type definitions, structures, and symbolic constants can be obtained defined for C and COBOL OLEDB: late 1990s - successor to ODBC, to provide an open standard for accessing all kinds of data
4
Using a Call-Level Interface (cont’d)
An application program needs to connect to the DB, pass SQL statements and receive the results e.g., struct in C Records used by the application program Environment created in preparation for connections to DB Connection created to connect to the DB exists within some environment Statement holds information about a single SQL statement includes an implied cursor, if the statement is a query exists within some connection Description holds information about either tuples or parameters Within an environment, there can be several connections Within a connection, there can be several statements Each statement may have several description records
5
Using a Call-Level Interface (cont’d)
Environment, Connection, Statement, Description Handle pointer to the record discussed in the previous slide types for the handles (provided in sqlcli.h) SQLHENV: for environment records SQLHDBC: for connection records SQLHSTMT: for statement records SQLHDESC: for description records Other defined types in sqlcli.h SQL_CHAR, SQL_INTEGER, etc
6
Using a Call-Level Interface (cont’d)
Creation of handles for records of environments, connections, and statements SQLAllocHandle(hType, hIn, hOut) hType: the type of handle desired SQL_HANDLE_ENV: for a new environment handle SQL_HANDLE_DBC: for a new connection handle SQL_HANDLE_STMT: for a new statement handle Details about how description records are set and used will not be discussed
7
Using a Call-Level Interface (cont’d)
hIn: handle of the higher-level in which the newly allocated handle lives SQL_NULL_HANDLE if want to create an environment handle environment handle within which the connection will exist if want to create a connection handle connection handle within which the statement will exist if want to create a statement handle hOut: address of the handle created by SQLAllocHandle()
8
Using a Call-Level Interface (cont’d)
(Ex) Beginning part of worthRanges() in SQL/CLI. #include sqlcli.h SLQHENV myEnv; SQLHDBC myCon; SQLHSTMT execStat; SQLRETURN errorCode1, errorCode2, errorCode3; errorCode1 = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &myEnv); if(!errorCode1) { errorCode2 = SQLAllocHandle(SQL_HANDLE_DBC, myEnv, &myCon); if(!errorCode2) errorCode3 = SQLAllocHandle(SQL_HANDLE_STMT, myCon, &execStat); }
9
Using a Call-Level Interface (cont’d)
Statement handle execStat represents the SQL statement (ex) SELECT netWorth FROM MovieExec; SQLAllocHandle() returns a value of SQLRETURN type 0 : no error nonzero values : in case of errors
10
Note: Preparation for accessing DB in ODBC
Not in the textbook Steps in preparation for accessing the database allocate an environment handle SQLAllocHandle(...) allocate a connection handle establish a connection SQLConnect(ConnectionHandle, *Servername, . . .) establish a connection to the target database connection needs to be established before allocating a statement handle allocate a statement handle prepare a workspace for interacting with DB create an empty connection
11
Using a Call-Level Interface (cont’d)
Processing statements the process of associating and executing SQL statements with statement handles is analogous to the dynamic SQL Prepare SQL statement SQLPrepare(sh, st, sl) sh : a statement handle st : pointer to a SQL statement string sl : length for the SQL statement string SQL_NTS : can be used if we do not know the length may think of “SQL variable” in the dynamic SQL as a statement handle
12
Using a Call-Level Interface (cont’d)
Execute a SQL statement SQLExecute(sh) statement to which handle sh refers to be executed Statement that sh refers to when INSERT or DELETE, execute directly when a SELECT query, the result of the query is placed somewhere, and there is an implicit cursor for the result. can fetch one tuple at a time as in real cursors
13
Using a Call-Level Interface (cont’d)
(ex) Consider worthRanges() again. Suppose we want to execute the following query by using SQL/CLI: SELECT netWorth FROM MovieExec; SQLPrepare(execStat, “SELECT netWorth FROM MovieExec”, SQL_NTS); SQLExecute(execStat); SQLExecDirect() combine SQLPrepare() and SQLExecute() SQLExecDirect(execStat,
14
Using a Call-Level Interface (cont’d)
Fetching data from a query result SQLFetch(sh) fetch tuples one at a time sh : a statement handle return a value that indicates success or an error SQL_NO_DATA: no tuple is fetched Where does the fetched tuple appear? its components go into one of description records associated with the SQL statement whose handle appears in the SQLFetch call we can extract components of each fetched tuple by binding each component to a host-language variable, before we begin fetching correspond to the FETCH statement in ESQL
15
Using a Call-Level Interface (cont’d)
Bind the columns to the host variables: SQLBindCol() SQLBindCol(sh, colNo, colType, pVar, varSize, varInfo) sh: the statement handle colNo: the number of the column within the tuple colType: the type of the column colNo pVar: a pointer to the host variable into which the value of column colNo is to be placed varSize: the length of the variable pointed to by pVar varInfo: a pointer for additional information about the value produced one SQLBindCol() for each attribute
16
Using a Call-Level Interface (cont’d)
(Ex) Function worthRanges(): Find the number of movie executives whose net worths fall into a certain number of digits. e.g., there are 10 movie executives whose net worths are in the range of the millions (i.e., 7 digits)
17
Using a Call-Level Interface (cont’d)
#include sqlcli.h void worthRanges() { int i, digits, counts[15]; SLQHENV myEnv; SQLHDBC myCon; SQLHSTMT execStat; SQL_INTEGER worth, worthInfo; SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &myEnv); SQLAllocHandle(SQL_HANDLE_DBC, myEnv, &myCon); /* SQLConnect(...): connect to database by using myCon */ SQLAllocHandle(SQL_HANDLE_STMT, myCon, &execStat) worth corresponds to the host variable
18
Using a Call-Level Interface (cont’d)
SQLPrepare(execStat, “SELECT netWorth FROM MovieExec”, SQL_NTS); SQLExecute(execStat); SQLBindCol(execStat, 1, SQL_INTEGER, &worth, sizeof(worth), &worthInfo); while(SQLFetch(execStat) != SQL_NO_DATA) { digits = 1; while(worth /= 10) > 0) digits++; if(digits <= 14) counts[digits]++ } for(i=0; i<15; i++) printf(“digits=%d: number of exec = %d\n”, i, counts[i]); binds the first column to the variable worth a constant representing no tuple fetched
19
Using a Call-Level Interface (cont’d)
can be skipped SQLGetData() another way of passing a query results to host variables similar to SQLBindCol() move components of a fetched tuple to host variables as needed fetch tuples without any binding takes same arguments as SQLBindCol(...) in order to have the same effect as SQLBindCol(), it must be used after each SQLFetch(...)
20
Note: Passing data Passing data between SQL and host variables
columns of the result tuple host language variables bind the columns to the host variables SQLBindCol() host language variables parameters in a SQL statement pass the host variables to parameters in a SQL query SQLBindParameter()
21
Using a Call-Level Interface (cont’d)
Passing parameters to queries: SQLBindParameter() SQLPrepare() use a question-mark “?” for a parameter the i-th question-mark represents the i-th parameter SQLBindParameter() the value of host variable the parameter in a SQL statement bind values to the places where the question-marks are found SQLExecute() execute the query with these bindings Parameters in SQL statements - host variables are used in ESQL - “?” are used in dynamic SQL similar to dynamic SQL
22
Using a Call-Level Interface (cont’d)
(Ex) In function getStudio(), write in CLI for the following: Obtain a name and an address of a studio, then insert them into the Studio table. /* get values for studioName and studioAddr */ SQLPrepare(myStat, “INSERT INTO Studio(name, address) VALUES(?, ?)”, SQL_NTS); SQLBindParameter(myStat, 1, ..., studioName, ...); SQLBindParameter(myStat, 2, ..., studioAddr, ...); SQLExecute(myStat); a statement handle bind the second parameter in myStat to the C variable studioAddr
23
JDBC JDBC(Java Database Connectivity) Objects in JDBC
JDBC and CLI: syntactic differences rather than semantics JDBC(Java Database Connectivity) for allowing Java programs to access SQL database similar to SQL/CLI, but object-oriented flavor Objects in JDBC DriverManager provides basic service for managing JDBC drivers Connection: object for connecting to DB Statement: object for SQL statements ResultSet: object for containing results of SQL query classes in java.sql analogous to a CLI environment record analogous to a CLI connection record analogous to a CLI statement record
24
JDBC (cont’d) First steps to use JDBC
make the JDBC classes available to the Java program import java.sql.*; /* include this line */ load a driver for the database system Class.forName() method Class.forName(<driver name>); the class for a named JDBC driver is loaded JDBC driver: is a software component that enables a Java application to interact with a DBMS, e.g., converts JDBC API into the API of each DBMS
25
JDBC (cont’d) (ex) get the driver for a Oracle database
Class.forName(“oracle.thin.Driver”) (ex) get the driver for a MySQL database Class.forName(“com.mysql.jdbc.Driver”) DriverManager.registerDriver() method: (ex) DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
26
JDBC (cont’d) establish a connection to DB: getConnection() method
apply the method getConnection to DriverManager a connection object is created Connection myCon = DriverManager.getConnection( <URL>, <user name>, <password>); <URL>: URL for DB to which you wish to connect by JDBC (ex) the form of the URL for connecting to a MySQL database jdbc:mysql://<host name>/<database name>
27
JDBC (cont’d) From a Connection object,
we can create statement objects: place SQL statements in those objects, bind values to SQL statement parameters, execute the SQL statements, which may return a result set object From the ResultSet object, we can examine the results, a tuple at a time
28
Note: JDBC Architecture
Not in the textbook Java Applications DriverManager Object getConnection(...) registerDriver(...) JDBC API creates provides service for managing JDBC drivers createStatement(...) prepareStatement(...) Connection Object JDBC Driver Manager creates JDBC Driver1 JDBC Driver2 JDBC Driver3 Statement Object executeQuery(...) executeUpdate(...) returns DBMS1 DBMS2 DBMS3 ResultSet Object getInt(...) getString(...)
29
JDBC (cont’d) Creating statements in JDBC createStatement()
createStatement(), prepareStatement(Q) the methods applied to a Connection object createStatement() returns a Statement object has no associated SQL statement yet prepareStatement(Q) Q is a SQL query as a string argument returns a PreparedStatement object factory methods that create statement objects (cf) SQLAllocHandle (..._STMT, ch, &sh ) (cf) SQLAllocHandle (..._STMT, ch, &sh ) SQLPrepare(sh, ‘SQL-string’, length)
30
JDBC (cont’d) Executing SQL statments executeQuery(Q), executeQuery()
executeUpdate(Q), executeUpdate() Meaning of “update” in executeUpdate() all statements that are not a query e.g., INSERT, DELETE, UPDATE, CREATE TABLE, etc. factory methods that create ResultSet objects
31
JDBC (cont’d) executeQuery(Q) executeQuery()
Q is a string of a SQL query applied to a Statement object returns a ResultSet object executeQuery() applied to a PreparedStatement object a SQL query associated with the prepared object is executed (cf) SQLExecDirect(sh, ‘SQL-string’, length) a set (actually bag) of tuples produced by Q (cf) SQLExecute(sh)
32
JDBC (cont’d) executeUpdate(U) executeUpdate()
applied to a Statement object, takes a string of a nonquery statement U and executes it executeUpdate() applied to a PreparedStatement object a nonquery statement associated with a prepared object is executed (cf) SQLExecDirect(sh, ‘SQL-string’, length) no ResultSet object is returned (cf) SQLExecute(sh)
33
JDBC (cont’d) (Ex) Consider worthRanges() again. Suppose we have a Connection object myCon, and we wish to execute the following query: SELECT netWorth FROM MovieExec; Execute the query without preparing a query Statement execStat = myCon.createStatement(); ResultSet worths = execStat.executeQuery( “SELECT netWorth FROM MovieExec”); Prepare the query and later execute it PreparedStatement execStat = myCon.prepareStatement( ResultSet worths = execStat.executeQuery();
34
JDBC (cont’d) (Ex) Execution of a nonquery Execute without preparation
there is a no ResultSet “Insert a tuple into StarsIn table.” Execute without preparation Statement starStat = myCon.createStatement(); starStat.executeUpdate(“INSERT INTO StarsIn VALUES(“ + “‘Remember the Titans’, 2000, ‘Denzel Washington’)” ); + is the Java operator that concatenate strings, which allows several lines of Java, as needed.
35
JDBC (cont’d) Prepare and later execute
PreparedStatement starStat = myCon.prepareStatement( “INSERT INTO StarsIn VALUES(‘Remember the Titans’,” + “2000, ‘Denzel Washington’)” ); starStat.executeUpdate();
36
JDBC (cont’d) Cursor operations in JDBC
there is an implicit cursor for the result of a query ResultSet class provides useful methods related with a cursor next() causes an implicit cursor to move to the next tuple (to the first tuple, the first time it is applied) getString(i), getInt(i), getFloat(i), etc return the i-th component of the tuple currently indicated by the cursor getString(“column-name”), getInt(“column-name”), etc (cf) SQLFetch(sh) (cf) SQLBindCol(. . .) or SQLGetData(. . .)
37
JDBC (cont’d) (Ex) Consider ResultSet worths in the previous example for part of worthRanges(): Statement execStat = myCon.createStatement(); ResultSet worths = execStat.executeQuery( “SELECT netWorth FROM MovieExec”); access tuples of the ResultSet worths one at a time while(worths.next()) { int worth = worths.getInt(1); /* process this net worth */ }; Initially, the cursor is positioned before the first row
38
JDBC (cont’d) Passing data between SQL and Java variables
columns of the query result tuple Java variables pass the column value of a query result tuple to a Java variable getString(), getInt() Java variables parameters of the SQL statement pass the value of a Java variable to a parameter of the query setString(), setInt() the query maintained in a PreparedStatement object
39
JDBC (cont’d) Parameter passing create a PreparedStatement object
similar to CLI, i.e., use a question mark “?” in a query, and then bind values to those variables create a PreparedStatement object use question-marks for parameters in a SQL statement the i-th question-mark represents the i-th parameter setString(i, v), setInt(i, v), etc bind the value v to the i-th parameter in the query (cf) SQLBindParameter(. . .)
40
JDBC (cont’d) (Ex) In function getStudio(), write in JDBC for the following: Obtain a name and an address of a studio, then insert them into the Studio table. PreparedStatement studioStat = myCon.prepareStatement( “INSERT INTO Studio(name, address) VALUES(?, ?)”); /* get values for variables studioName and studioAddr from the user */ studioStat.setString(1, studioName); studioStat.setString(2, studioAddr); studioStat.executeUpdate();
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.