Module-3 DB Application
Module-3 DB Application
Chapter 6
Impedance mismatch:
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++. (Though now: STL)
SQL supports a mechanism called a cursor to
handle this.
Ease of use.
Language constructs:
Connecting to a database:
EXEC SQL CONNECT
Declaring variables:
EXEC SQL BEGIN (END) DECLARE SECTION
Statements:
EXEC SQL Statement;
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
Embedded SQL: Variables
Example:
char c_sqlstring[]=
{“DELETE FROM Sailors WHERE rating>5”};
EXEC SQL PREPARE readytogo FROM :c_sqlstring;
EXEC SQL EXECUTE readytogo;
Supposedly DBMS-neutral
a “driver” traps the calls and translates them into DBMS-
specific code
database can be across a network
Disadvantages:
The module libraries are specific to the
programming language and environment. Thus,
portability is compromised greatly.
Example:
String url=“jdbc:oracle:www.bookstore.com:3083”;
Connection con;
try{
con = DriverManager.getConnection(url,usedId,password);
} catch SQLException excpt { …}
PreparedStatement class:
Precompiled, parametrized SQL statements:
Structure is fixed
Values of parameters are determined at run-time
ResultSet rs=pstmt.executeQuery(sql);
// rs is now a cursor
While (rs.next()) {
// process the data
}
DatabaseMetaData md = con.getMetaData();
// print information about the driver:
System.out.println(
“Name:” + md.getDriverName() +
“version: ” + md.getDriverVersion());
/**
* This is a sample program with jdbc odbc Driver
*/
public class localdemo {
java.sql.Connection c = DriverManager.getConnection(url);
java.sql.ResultSetMetaData md = rs.getMetaData();
while(rs.next()) {
System.out.print("\nTUPLE: | ");
for(int i=1; i<= md.getColumnCount(); i++) {
System.out.print(rs.getString(i) + " | ");
}
}
rs.close();
} catch(Exception e) {
e.printStackTrace();
}
}
};
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
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 x = {
SELECT name, rating INTO :name, :rating
FROM Books WHERE sid = :sid;
Compare to JDBC:
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)
Advantages:
The development environment is not tied to a
particular DBMS, operating sytem, or even a
particular development environment.
Disadvantages:
Some low-level optimization may be more
difficult or impossible to achieve.
JDBC: SQLJ:
CallableStatement cstmt= #sql iterator ShowSailors(…);
con.prepareCall(“{call ShowSailors showsailors;
ShowSailors});
#sql showsailors={CALL
ResultSet rs = ShowSailors};
cstmt.executeQuery();
while (showsailors.next()) {
while (rs.next()) {
…
…
}
}