42
BD05/06 BD05/06 Database Application Database Application Development Development Embedded SQL Embedded SQL ODBC ODBC JDBC JDBC Application architectures Application architectures

BD05/06 Database Application Development Embedded SQL ODBC JDBC Application architectures

Embed Size (px)

Citation preview

Page 1: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Database Application Database Application DevelopmentDevelopment

Embedded SQLEmbedded SQL ODBC ODBC JDBCJDBC Application architecturesApplication architectures

Page 2: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

SQL in Application CodeSQL in Application Code

SQL commands can be called from SQL commands can be called from within a host language (e.g., C++ or within a host language (e.g., C++ or Java) program.Java) program. SQL statements can refer to SQL statements can refer to host variableshost variables Must include a statement to Must include a statement to connectconnect to the to the

right database.right database. Two main integration approaches:Two main integration approaches:

1.1.Embed SQL in the host language Embed SQL in the host language (Embedded SQL, SQLJ)(Embedded SQL, SQLJ)

2.2.Create special API to call SQL commands Create special API to call SQL commands (JDBC)(JDBC)

Page 3: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Impedance mismatchImpedance mismatch

SQL relations are SQL relations are (multi-) sets of (multi-) sets of recordsrecords, with no , with no a priori a priori bound on the bound on the number of records. No such data number of records. No such data structure exist traditionally in procedural structure exist traditionally in procedural programming languages such as C++. programming languages such as C++. SQL supports a mechanism called a SQL supports a mechanism called a cursorcursor

to handle this.to handle this.

Data typesData types of SQL and host language of SQL and host language are distinctare distinct There must be a conversion mechanismThere must be a conversion mechanism

Page 4: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Embedded SQLEmbedded SQL The SQL standard defines The SQL standard defines embeddings of SQLembeddings of SQL in a in a

variety of programming languagesvariety of programming languages A language to which SQL queries are embedded is A language to which SQL queries are embedded is

referred to as a referred to as a host host languagelanguage, and the SQL structures , and the SQL structures in the host language comprise in the host language comprise embedded embedded SQLSQL

EXEC SQLEXEC SQL statement is used to identify embedded statement is used to identify embedded SQL request to the preprocessorSQL request to the preprocessor

EXEC SQL <embedded SQL statement > END-EXECEXEC SQL <embedded SQL statement > END-EXEC

Note: this varies by language. E.g. the Java embedding usesNote: this varies by language. E.g. the Java embedding uses # SQL { …. } ; # SQL { …. } ;

The statement The statement SQL INCLUDESQL INCLUDE is placed in the is placed in the program to identify where the preprocessor inserts program to identify where the preprocessor inserts special variables for communication between the special variables for communication between the program and the DB systemprogram and the DB system

Page 5: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Example QueryExample Query

Specify the query in SQL and declare a Specify the query in SQL and declare a cursorcursor for it for it

EXEC SQLEXEC SQL

declare declare cc cursor for cursor for select customer-name, customer-cityselect customer-name, customer-cityfrom depositor, customer, accountfrom depositor, customer, accountwhere depositor.customer-name = where depositor.customer-name = customer.customer-name customer.customer-name and depositor account-number = and depositor account-number = account.account-numberaccount.account-number

and account.balance > :amountand account.balance > :amount

END-EXECEND-EXEC

From within a host language, find the names and cities of customers with more than the variable amount dollars in some account.

Page 6: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Embedded SQL (Cont.)Embedded SQL (Cont.) The The openopen statement causes the query to be evaluated statement causes the query to be evaluated

EXEC SQL open EXEC SQL open c c END-EXECEND-EXEC The The fetchfetch statement causes the values of one tupleto statement causes the values of one tupleto

be placed on host language variables.be placed on host language variables.EXEC SQL fetch EXEC SQL fetch c c into :into :cn, :cccn, :cc END-EXEC END-EXEC

Repeated calls to Repeated calls to fetchfetch get successive tuples in the query get successive tuples in the query resultresult A variable called SQLSTATE gets set to ‘02000’ to indicate A variable called SQLSTATE gets set to ‘02000’ to indicate

no more data is availableno more data is available The The closeclose statement causes the database system to statement causes the database system to

delete the temporary relationdelete the temporary relationEXEC SQL close EXEC SQL close cc END-EXEC END-EXEC

Note: above details vary with language. E.g. the Java embedding Note: above details vary with language. E.g. the Java embedding defines Java iterators to step through result tuples.defines Java iterators to step through result tuples.

Page 7: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Updates Through CursorsUpdates Through Cursors

Can update tuples fetched by cursor by declaring that the cursor is for update

declare c cursor for select * from account where branch-name = ‘Perryridge’ for update

To update tuple at the current location of cursor

update account set balance = balance + 100 where current of c

Page 8: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Dynamic SQLDynamic SQL Allows programs to construct and submit SQL queries Allows programs to construct and submit SQL queries

at at run-time.run-time. Example of the use of dynamic “SQL from within a C Example of the use of dynamic “SQL from within a C

program.program.

char * sqlprog = char * sqlprog = ““update account set update account set balance = balance * 1.05 where balance = balance * 1.05 where account-account-number = ?number = ?“;“;EXEC SQL prepareEXEC SQL prepare dynprog from :sqlprog; dynprog from :sqlprog;char account [10] = char account [10] = ““ A-101 A-101 ““;;EXEC SQL executeEXEC SQL execute dynprog using :account; dynprog using :account;

The dynamic SQL program contains a The dynamic SQL program contains a ??, which is a , which is a place holder for a value that is provided when the SQL place holder for a value that is provided when the SQL program is executed.program is executed.

Page 9: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Database APIs: Alternative Database APIs: Alternative to embeddingto embedding

Rather than modify compiler, add library with Rather than modify compiler, add library with database calls (API)database calls (API)

Special Special standardized interfacestandardized interface Pass SQL strings from language, presents Pass SQL strings from language, presents

result sets in a language-friendly wayresult sets in a language-friendly way

Ex: Sun’s Ex: Sun’s JDBCJDBC: : Java API (set of Java API (set of classes/interfaces in java.sql package)classes/interfaces in java.sql package)

Supposedly DBMS-neutral (portable)Supposedly DBMS-neutral (portable) a a driverdriver traps the calls and translates them into traps the calls and translates them into

DBMS-specific codeDBMS-specific code

Page 10: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

ODBCODBC

Open DataBase Connectivity (ODBC) is Open DataBase Connectivity (ODBC) is a standard for application program to a standard for application program to communicate with a database server.communicate with a database server.

Application program interface (Application program interface (APIAPI) to:) to: open a connection with a database, open a connection with a database, send queries and updates, send queries and updates, get back results.get back results.

Applications such as GUI, spreadsheets, Applications such as GUI, spreadsheets, etc. can use ODBCetc. can use ODBC

Page 11: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

ODBC (Cont.)ODBC (Cont.) Each database system supporting ODBC provides a Each database system supporting ODBC provides a

"driver" library"driver" library that must be linked with the client that must be linked with the client program.program. When client program makes an ODBC API call, the code in When client program makes an ODBC API call, the code in

the library communicates with the server to carry out the the library communicates with the server to carry out the requested action, and fetch results.requested action, and fetch results.

ODBC program first allocates an SQL environment, ODBC program first allocates an SQL environment, then a database connection handle.then a database connection handle. Opens database connection using Opens database connection using SQLConnect()SQLConnect() with with

the following parameters:the following parameters:• connection handle, the server to which to connect, the connection handle, the server to which to connect, the

user identifier, password user identifier, password

Page 12: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Example: ODBC CodeExample: ODBC Codeint ODBCexample()int ODBCexample() {{

RETCODE error;RETCODE error;

HENV env; /* environment */ HENV env; /* environment */

HDBC conn; /* database connection */ HDBC conn; /* database connection */

SQLAllocEnv(&env); /* allocates an SQL environment */SQLAllocEnv(&env); /* allocates an SQL environment */

SQLAllocConnect(env, &conn); /* allocates a DB conn. handle SQLAllocConnect(env, &conn); /* allocates a DB conn. handle */*/

SQLConnect(conn, "aura.bell-labs.com", SQL_NTS, "avi", SQLConnect(conn, "aura.bell-labs.com", SQL_NTS, "avi", SQL_NTS, "avipasswd", SQL_NTS); SQL_NTS, "avipasswd", SQL_NTS);

{{Main body of programMain body of program… }… }

SQLDisconnect(conn); SQLDisconnect(conn);

SQLFreeConnect(conn); SQLFreeConnect(conn);

SQLFreeEnv(env); SQLFreeEnv(env);

}}

Page 13: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

ODBC Code (Cont.)ODBC Code (Cont.) Program sends SQL commands using Program sends SQL commands using SQLExecDirectSQLExecDirect Result tuples are fetched using Result tuples are fetched using SQLFetch()SQLFetch() SQLBindCol()SQLBindCol() binds C language variables to attributes binds C language variables to attributes

of the query result of the query result When a tuple is fetched, its attribute values are automatically When a tuple is fetched, its attribute values are automatically

stored in corresponding C variables.stored in corresponding C variables. Arguments to Arguments to SQLBindCol()SQLBindCol()

ODBC stmt variable, attribute position in query resultODBC stmt variable, attribute position in query result The type conversion from SQL to C. The type conversion from SQL to C. The address of the variable. The address of the variable. For variable-length types like character arrays, the maximum For variable-length types like character arrays, the maximum

length of the variable and location to store actual length.length of the variable and location to store actual length. Good programming requires checking results of every Good programming requires checking results of every

function call for errors; we have omitted most checks function call for errors; we have omitted most checks for brevity.for brevity.

Page 14: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Example: Main body of programExample: Main body of program char branchname[80];char branchname[80]; float balance;float balance; int lenOut1, lenOut2;int lenOut1, lenOut2; HSTMT stmt; HSTMT stmt; SQLAllocStmtSQLAllocStmt (conn, &stmt); (conn, &stmt); char * sqlquery = "select branch_name, sum (balance) char * sqlquery = "select branch_name, sum (balance)

from account from account group by branch_name"; group by branch_name";

error = error = SQLExecDirectSQLExecDirect(stmt, sqlquery, SQL_NTS);(stmt, sqlquery, SQL_NTS); if (error == if (error == SQL_SUCCESSSQL_SUCCESS) {) {

SQLBindColSQLBindCol(stmt, 1, SQL_C_CHAR, branchname , 80, (stmt, 1, SQL_C_CHAR, branchname , 80, &lenOut1); &lenOut1); SQLBindColSQLBindCol(stmt, 2, SQL_C_FLOAT, &balance, 0, (stmt, 2, SQL_C_FLOAT, &balance, 0, &lenOut2); &lenOut2);

while (while (SQLFetchSQLFetch(stmt) >= (stmt) >= SQL_SUCCESSSQL_SUCCESS) {) { printf (" %s %g\n", branchname, balance); printf (" %s %g\n", branchname, balance); } }}}SQLFreeStmtSQLFreeStmt(stmt, SQL_DROP); (stmt, SQL_DROP);

Page 15: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

More ODBC FeaturesMore ODBC Features Prepared StatementPrepared Statement

SQL statement prepared: compiled at the databaseSQL statement prepared: compiled at the database Can have placeholders: insert into account values(?,?,?)Can have placeholders: insert into account values(?,?,?) Repeatedly executed with actual values for the placeholdersRepeatedly executed with actual values for the placeholders

Metadata featuresMetadata features finding all the relations in the database andfinding all the relations in the database and finding the names and types of columns of a query result or finding the names and types of columns of a query result or

a relation in the database.a relation in the database. By default, each SQL statement is treated as a By default, each SQL statement is treated as a

separate transaction that is committed automatically.separate transaction that is committed automatically. Can Can turn off automatic committurn off automatic commit on a connection on a connection

• SQLSetConnectOption(conn, SQL_AUTOCOMMIT, 0)SQLSetConnectOption(conn, SQL_AUTOCOMMIT, 0) transactions must then be committed or rolled back explicitly transactions must then be committed or rolled back explicitly

by by • SQLTransact(conn, SQL_COMMIT) orSQLTransact(conn, SQL_COMMIT) or• SQLTransact(conn, SQL_ROLLBACK)SQLTransact(conn, SQL_ROLLBACK)

Page 16: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

ODBC Conformance LevelsODBC Conformance Levels

Conformance levels specify subsets of Conformance levels specify subsets of the functionality defined by the standard.the functionality defined by the standard. CoreCore Level 1 requires support for metadata Level 1 requires support for metadata

queryingquerying Level 2 requires ability to send and retrieve Level 2 requires ability to send and retrieve

arrays of parameter values and more arrays of parameter values and more detailed catalog information.detailed catalog information.

SQL Call Level Interface (CLI) standard SQL Call Level Interface (CLI) standard similar to ODBC interface, but with some similar to ODBC interface, but with some minor differences.minor differences.

Page 17: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

JDBCJDBC

Java API for communicating with database Java API for communicating with database systems supporting SQLsystems supporting SQL

Supports a variety of features for querying Supports a variety of features for querying and updating data, and for retrieving query and updating data, and for retrieving query resultsresults

Supports metadata retrieval, such as Supports metadata retrieval, such as querying about relations present in the querying about relations present in the database and the names and types of database and the names and types of relation attributesrelation attributes

Page 18: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

JDBC: ArchitectureJDBC: Architecture

Four architectural components:Four architectural components: ApplicationApplication initiates and terminates initiates and terminates

connections, submits SQL statements, and connections, submits SQL statements, and retrieves results through the JDBC APIretrieves results through the JDBC API

Driver managerDriver manager handles initialization, loads handles initialization, loads JDBC driverJDBC driver

DriverDriver connects to data source, transmits connects to data source, transmits requests and returns/translates results and requests and returns/translates results and error codeserror codes

Data sourceData source processes SQL statements from processes SQL statements from the driver and returns resultsthe driver and returns results

Page 19: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Steps to submit a database Steps to submit a database queryquery

1)1)Select a data sourceSelect a data source

2)2)Dynamically load the JDBC driverDynamically load the JDBC driver

3)3)Connect to the data sourceConnect to the data source

4)4)Execute SQL statementsExecute SQL statements

5)5)Disconnect from the data sourceDisconnect from the data source

Page 20: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

2. JDBC Driver Manager2. JDBC Driver Manager All drivers are managed by the All drivers are managed by the DriverManagerDriverManager

class that keeps a list of all currently loaded class that keeps a list of all currently loaded driversdrivers

Has methods: Has methods: registerDriver, registerDriver, deRegisterDriver, getDriversdeRegisterDriver, getDrivers

Loading a JDBC driver:Loading a JDBC driver: In the Java code:In the Java code:Class.forName(“oracle/jdbc.driver.OracClass.forName(“oracle/jdbc.driver.Oracledriver”);ledriver”);

When starting the Java application:When starting the Java application:-Djdbc.drivers=oracle/jdbc.driver-Djdbc.drivers=oracle/jdbc.driver

Page 21: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

3. Connections in JDBC3. Connections in JDBC We interact with a data source through We interact with a data source through

sessions. A session is started through the sessions. A session is started through the creation of a creation of a ConnectionConnection object. object.

A Connection is specified through a JDBC URL:A Connection is specified through a JDBC URL:jdbc:<subprotocol>:<otherParameters>jdbc:<subprotocol>:<otherParameters>

Example of code to establish a connection to Oracle:Example of code to establish a connection to Oracle:String url=“jdbc:oracle:www.bookstore.com:3083”;String url=“jdbc:oracle:www.bookstore.com:3083”;Connection con;Connection con;try{try{

con = con = DriverManager.getConnection(url,usedId,password);DriverManager.getConnection(url,usedId,password);

} catch SQLException excpt { …}} catch SQLException excpt { …}

Page 22: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Connection Class InterfaceConnection Class Interfacepublic int public int getTransactionIsolation()getTransactionIsolation()

void void setTransactionIsolation(int level)setTransactionIsolation(int level)Sets isolation level for the current connection.Sets isolation level for the current connection.

public boolean public boolean getReadOnly()getReadOnly()

void void setReadOnly (boolean b)setReadOnly (boolean b)Specifies whether transactions in this connection are read-Specifies whether transactions in this connection are read-onlyonly

public boolean public boolean getAutoCommit()getAutoCommit()

void void setAutoCommit(boolean b)setAutoCommit(boolean b)If autocommit is set, then each SQL statement is If autocommit is set, then each SQL statement is considered its own transaction. Otherwise, a transaction is considered its own transaction. Otherwise, a transaction is committed using committed using commit()commit(), or aborted using , or aborted using rollback()rollback()..

public booleanpublic boolean isClosed() isClosed()Checks whether connection is still open.Checks whether connection is still open.

Page 23: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

4. Executing SQL Statements4. Executing SQL Statements Three different ways of executing SQL Three different ways of executing SQL

statements:statements: StatementStatement PreparedStatementPreparedStatement CallableStatmentCallableStatment (stored procedures) (stored procedures)

PreparedStatementPreparedStatement class: class:Precompiled, parametrized SQL statements Precompiled, parametrized SQL statements that can be executed several times:that can be executed several times: Structure is fixedStructure is fixed Values of parameters are determined at run-timeValues of parameters are determined at run-time

Page 24: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Statements and ResultSetStatements and ResultSet

executeUpdateexecuteUpdate only returns the number of only returns the number of affected recordsaffected records

executeQueryexecuteQuery returns data, encapsulated returns data, encapsulated in a in a ResultSetResultSet object (a cursor) object (a cursor)

Statement stmt = conn.createStatement();String sql = "select branch_name, avg(balance) from account group by branch_name"

ResultSet rs=stmt.executeQuery(sql);ResultSet rs=stmt.executeQuery(sql);// rs is now a cursor// rs is now a cursorWhile (rs.next()) {While (rs.next()) { // process the data// process the data}}

Page 25: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

ResultSet (Contd.)ResultSet (Contd.)

A ResultSet is a very powerful cursor:A ResultSet is a very powerful cursor:

previous()previous(): moves one row back: moves one row back

absolute(int num)absolute(int num): moves to the row : moves to the row with the specified numberwith the specified number

relative (int num)relative (int num): moves forward or : moves forward or backward relative to the current positionbackward relative to the current position

first()first() and and last()last(): moves to the : moves to the first/last rowfirst/last row

Page 26: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Matching Java and SQL Data Matching Java and SQL Data TypesTypes

getTimestamp()java.sql.TimeStampTIMESTAMP

getTime()java.sql.TimeTIME

getDate()java.sql.DateDATE

getFloat()DoubleREAL

getInt()IntegerINTEGER

getDouble()DoubleFLOAT

getDouble()DoubleDOUBLE

getString()StringVARCHAR

getString()StringCHAR

getBoolean()BooleanBIT

ResultSet get methodJava classSQL Type

Page 27: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

JDBC: Exceptions and WarningsJDBC: Exceptions and Warnings

Most of java.sql JDBC methods can Most of java.sql JDBC methods can throw and throw and SQLExceptionSQLException if an error if an error occurs.occurs.

SQLException methods: SQLException methods: getMessage(), getSQLState(), getMessage(), getSQLState(), getErrorCode(), getNextException()getErrorCode(), getNextException()

SQLWarningSQLWarning is a subclass of is a subclass of SQLException; not as severe (they are SQLException; not as severe (they are not thrown and their existence has to be not thrown and their existence has to be explicitly tested)explicitly tested)

Page 28: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

JDBC CodeJDBC Codepublic static void JDBCexample(String dbid, String public static void JDBCexample(String dbid, String

userid, String passwd) { userid, String passwd) {

try { try {

/* load driver *//* load driver */ Class.forNameClass.forName ("oracle.jdbc.driver.OracleDriver"); ("oracle.jdbc.driver.OracleDriver"); Connection conn = Connection conn = DriverManager.getConnectionDriverManager.getConnection( ( "jdbc:oracle:thin:@aura.bell-labs.com:2000:bankdb", "jdbc:oracle:thin:@aura.bell-labs.com:2000:bankdb", userid, passwd); userid, passwd);

StatementStatement stmt = conn. stmt = conn.createStatementcreateStatement(); ();

… … Do Actual Work ….Do Actual Work ….

stmt.close();stmt.close();

conn.close();conn.close();

}}

catch (SQLException sqle) { catch (SQLException sqle) {

System.out.println("SQLException : " + sqle);System.out.println("SQLException : " + sqle);

}}

}}

Page 29: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

JDBC Code (Cont.)JDBC Code (Cont.) UpdateUpdate to database to databasetry { try {

stmt.executeUpdatestmt.executeUpdate("insert into account values("insert into account values ('A-9732', 'Perryridge', 1200)"); ('A-9732', 'Perryridge', 1200)");

} catch (} catch (SQLExceptionSQLException sqle) { sqle) {

System.out.println("Could not insert tuple. " + System.out.println("Could not insert tuple. " + sqle);sqle);

}} Execute queryExecute query and fetch and print results and fetch and print results ResultSet rset = ResultSet rset = stmt.executeQuerystmt.executeQuery( "select ( "select

branch_name, avg(balance) from account branch_name, avg(balance) from account group by branch_name"); group by branch_name");

while (while (rset.nextrset.next()) {()) {System.out.println(System.out.println(rset.getStringrset.getString("branch_name") + " ("branch_name") + "

" + " + rset.getFloatrset.getFloat(2));(2));

}}

Page 30: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

JDBC Code Details JDBC Code Details

Getting result fields:Getting result fields: rs.getStringrs.getString(“branchname”)(“branchname”) and and rs.getStringrs.getString(1)(1) equivalent if equivalent if branchname is the first argument of select branchname is the first argument of select result.result.

Dealing with Null valuesDealing with Null valuesint a = int a = rs.getIntrs.getInt(“a”);(“a”);

if (if (rs.wasNullrs.wasNull()) ()) Systems.out.println(“Got null Systems.out.println(“Got null value”);value”);

Page 31: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Prepared StatementPrepared Statement Allows queries to be Allows queries to be compiled and executed multiple timescompiled and executed multiple times

with different argumentswith different argumentsPreparedStatementPreparedStatement pStmt = pStmt = conn.prepareStatementconn.prepareStatement( “insert into account ( “insert into account values(?,?,?)”); values(?,?,?)”);

pStmt.setStringpStmt.setString(1, "A-9732"); (1, "A-9732");

pStmt.setStringpStmt.setString(2, "Perryridge"); (2, "Perryridge");

pStmt.setIntpStmt.setInt(3, 1200); (3, 1200);

pStmt.executeUpdatepStmt.executeUpdate(); ();

pStmt.setStringpStmt.setString(1, "A-9733"); (1, "A-9733");

pStmt.executeUpdatepStmt.executeUpdate(); ();

Beware: If value to be stored in database contains a single Beware: If value to be stored in database contains a single quote or other special character, prepared statements work quote or other special character, prepared statements work fine, but creating a query string and executing it directly fine, but creating a query string and executing it directly would result in a syntax error!would result in a syntax error!

Page 32: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Example of PreparedStatementExample of PreparedStatement

String sql=“INSERT INTO Sailors String sql=“INSERT INTO Sailors VALUES(?,?,?,?)”;VALUES(?,?,?,?)”;

PreparedStatment PreparedStatment pstmt=con.prepareStatement(sql);pstmt=con.prepareStatement(sql);

pstmt.clearParameters();pstmt.clearParameters();

pstmt.setInt(1,sid);pstmt.setInt(1,sid);

pstmt.setString(2,sname);pstmt.setString(2,sname);

pstmt.setInt(3, rating);pstmt.setInt(3, rating);

pstmt.setFloat(4,age);pstmt.setFloat(4,age);

// we know that no rows are returned, thus we use // we know that no rows are returned, thus we use executeUpdate()executeUpdate()

int numRows = pstmt.executeUpdate();int numRows = pstmt.executeUpdate();

Page 33: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Transactions in JDBCTransactions in JDBC

As with ODBC, each statement gets As with ODBC, each statement gets committed automatically in JDBCcommitted automatically in JDBC

To To turn off auto committurn off auto commit use use conn.setAutoCommitconn.setAutoCommit(false); (false);

To To commit or abort transactionscommit or abort transactions useuse conn.commitconn.commit() or () or conn.rollbackconn.rollback()()

To To turn auto committurn auto commit on again, use on again, use conn.setAutoCommitconn.setAutoCommit(true); (true);

Page 34: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Procedure and Function Calls in Procedure and Function Calls in JDBCJDBC

JDBC provides a class JDBC provides a class CallableStatementCallableStatement which allows SQL stored procedures and which allows SQL stored procedures and functions to be invoked.functions to be invoked.

CallableStatementCallableStatement cs1 = cs1 = conn.prepareCallconn.prepareCall(“{call proc(?,?)}”);(“{call proc(?,?)}”);

CallableStatementCallableStatement cs2 = cs2 = conn.prepareCallconn.prepareCall(“{?=call func(?,?)}”);(“{?=call func(?,?)}”);

Page 35: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Result Set MetaDataResult Set MetaData The class The class ResultSetMetaDataResultSetMetaData provides information provides information

about all the columns of the ResultSet.about all the columns of the ResultSet. Instance of this class is obtained by Instance of this class is obtained by getMetaDatagetMetaData( )( )

function of ResultSet.function of ResultSet. Provides functions for getting Provides functions for getting number of columns, number of columns,

column name, type, precision, scale, tablecolumn name, type, precision, scale, table from which from which the column is derived etc.the column is derived etc.

ResultSetMetaDataResultSetMetaData rsmd = rsmd = rs.getMetaDatars.getMetaData ( ); ( );

for ( int i = 1; i <= for ( int i = 1; i <= rsmd.getColumnCountrsmd.getColumnCount( ); i++ ( ); i++ ) {) {

String name = String name = rsmd.getColumnName(irsmd.getColumnName(i););

String typeName = String typeName = rsmd.getColumnTypeNamersmd.getColumnTypeName(i);(i);

}}

Page 36: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Database Meta DataDatabase Meta Data The class The class DatabaseMetaDataDatabaseMetaData provides information about provides information about

database relationsdatabase relations Has functions for getting all tables, all columns of the table, Has functions for getting all tables, all columns of the table,

primary keys, foreign keys, etc.primary keys, foreign keys, etc.Ex: to print column names and types of a relation Ex: to print column names and types of a relation

DatabaseMetaDataDatabaseMetaData dbmd = dbmd = conn.getMetaDataconn.getMetaData( );( );ResultSetResultSet rs = rs = dbmd.getColumnsdbmd.getColumns(null, “BANK-DB”, (null, “BANK-DB”,

“account”, “%” ); “account”, “%” );//Arguments: catalog, schema-pattern, table-pattern, //Arguments: catalog, schema-pattern, table-pattern,

column-patterncolumn-pattern// Returns: 1 row for each column, with several// Returns: 1 row for each column, with several// attributes such as COLUMN_NAME, TYPE_NAME, etc.// attributes such as COLUMN_NAME, TYPE_NAME, etc.while (while (rs.nextrs.next( )) {( )) {

System.out.println( System.out.println( rs.getStringrs.getString(“COLUMN_NAME”), (“COLUMN_NAME”), rs.getStringrs.getString(“TYPE_NAME”)(“TYPE_NAME”)

}}

Page 37: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Schemas, Catalogs, and Schemas, Catalogs, and EnvironmentsEnvironments

Three-level hierarchy for naming Three-level hierarchy for naming relations. relations. Database contains multiple Database contains multiple catalogscatalogs each catalog can contain multiple each catalog can contain multiple schemasschemas SQL objects such as relations and views SQL objects such as relations and views

are contained within a schemaare contained within a schema e.g. catalog5.bank-schema.accounte.g. catalog5.bank-schema.account Each user has a default catalog and Each user has a default catalog and

schema, and the combination is unique schema, and the combination is unique to the user.to the user.

Default catalog and schema are set up Default catalog and schema are set up for a connectionfor a connection

Catalog and schema can be omitted, Catalog and schema can be omitted, defaults are assumeddefaults are assumed

Multiple versions of an application (e.g. Multiple versions of an application (e.g. production and test) can run under production and test) can run under separate schemasseparate schemas

Page 38: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Application ArchitecturesApplication Architectures

Applications can be built using one of two Applications can be built using one of two architectures:architectures:

Two tier modelTwo tier model Application program running at user site Application program running at user site

directly uses JDBC/ODBC to communicate directly uses JDBC/ODBC to communicate with the databasewith the database

Three tier modelThree tier model Users/programs running at user sites Users/programs running at user sites

communicate with an application server. communicate with an application server. The application server in turn The application server in turn communicates with the databasecommunicates with the database

Page 39: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Two-tier ModelTwo-tier Model E.g. Java code runs at client site and uses E.g. Java code runs at client site and uses

JDBC to communicate with the serverJDBC to communicate with the server BenefitsBenefits::

flexible, need not be restricted to predefined flexible, need not be restricted to predefined queriesqueries

ProblemsProblems:: Security: passwords available at client site, all Security: passwords available at client site, all

database operation possibledatabase operation possible More code shipped to clientMore code shipped to client Not appropriate across organizations, or in large Not appropriate across organizations, or in large

ones like universitiesones like universities

Page 40: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Three Tier ModelThree Tier ModelCGI Program

DatabaseServer

Application/HTTPServer

ServletsJDBC

Network

Client Client Client

HTTP/Application Specific Protocol

Page 41: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

Three-tier Model (Cont.)Three-tier Model (Cont.)

E.g. Web client + Java Servlet using JDBC to E.g. Web client + Java Servlet using JDBC to talk with database servertalk with database server

Client sends request over http or application-Client sends request over http or application-specific protocolspecific protocol

Application or Web server receives requestApplication or Web server receives request Request handled by CGI program or servletsRequest handled by CGI program or servlets Security handled by application at serverSecurity handled by application at server Simple client, but only packaged transactionsSimple client, but only packaged transactions

Page 42: BD05/06 Database Application Development  Embedded SQL  ODBC  JDBC  Application architectures

BD05/06BD05/06

ReferencesReferences

Database Management Systems, J. Database Management Systems, J. Gerke and R. Ramakrishnan, Chapt. 6 Gerke and R. Ramakrishnan, Chapt. 6

JDBC tutorial (como o indicado na JDBC tutorial (como o indicado na página da cadeira)página da cadeira)