Database in Applica.on Deelopment Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata
SQL from Programs SQL commands can be called from within a host language program C, C++, Jaa, Two main appraoches Embed SQL in the host language Embedded SQL, SQLJ, We will NOT coer this, self learn if you need Special API to call SQL commands JDBC 2
Impedance mismatch Database relations are (multi-) sets of records No a-priori bound on the number of records Traditionally programming languages did not hae any inbuilt way to handle this Now Vector, List etc are aailable Cursor: SQL supports a mechanism to handle this problem 3
Cursors Can declare a cursor on a relation or query statement which generates a relation Can Open a cursor Can Repeatedly fetch a tuple, then moe the cursor until all the tuples are retrieed Can use a special clause ORDER_BY to control the order in which the tuples are returned Can also modify / delete tuples pointed to by a cursor 4
Database APIs SQL embedding requires modification to the compiler Database APIs: add library with database calls (API) Special standardized interface: procedures / objects Pass SQL strings from language, presents result sets in a language friendly way Examples JDBC (Jaa Database Connectiity) ODBC (Open Database Connectiity) works with C, C++, C#, and Visual Basic Other API s such as ADO.NET sit on top of ODBC 5
JDBC Jaa DataBase Connectiity A Jaa API for communicating with database systems supporting SQL. Supports a ariety of features for querying and updating data, and for retrieing query results Also supports metadata retrieal, such as querying about relations present in the database and the names and types of relation attributes 6
ODBC Open DataBase Connectiity (ODBC) standard standard for application program to communicate with a database serer. application program interface (API) to open a connection with a database, send queries and updates, get back results. Applications such as GUI, spreadsheets, etc. can use ODBC 7
JDBC Architecture 1. Application Initiates and terminates connections Submits SQL statements 2. Drier manager Loads JDBC drier 3. Drier A software program Connects to data source, transmits requests and returns / translates results or error codes 4. Data source Processes SQL statements 8
Four types of JDBC driers 1. Bridge Translates SQL commands into non-natie API Code for JDBC drier needs to be aailable on each client 2. Direct translation to natie API, non-jaa drier: Translates SQL commands to natie API of data source Need OS-specific binary on each client 3. Network bridge: Send commands oer the network to a middleware serer that talks to the data source Needs only small JDBC drier at each client 4. Direction translation to natie API ia Jaa drier: Conerts JDBC calls directly to network protocol used by DBMS Needs DBMS-specific Jaa drier at each client 9
SubmiCng a database query 1. Load the JDBC drier 2. Connect to the data source 3. Execute the SQL statements 1. Exception mechanism to handle errors 4. ( Close the connection ) 10
JDBC drier management Driers are managed by the DrierManager class Loading a JDBC drier Jaa code: Class.forName( oracle/jdbc.drier.oracledrier) Starting the Jaa application: -Djdbc.driers=oracle/jdbc.drier 11
Connec.ons Connection: a logical session JDBC URL: jdbc:<subprotocol>:<other_params> Example: String url= jdbc:oracle:www.dbserer.com:3083 ; Connection con; try{ con = DrierManager.getConnection(url,userId,pw); } catch SQLException e { System.err.println(e.getMessage()); } 12
Connec.on Class Interface public int gettransactionisolation() and oid settransactionisolation(int leel) Sets isolation leel for the current connection. public boolean getreadonly() and oid setreadonly(boolean b) Specifies whether transactions in this connection are read-only 13
Connec.on Class Interface public boolean getautocommit() and oid 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 14
Mul.ple connec.ons Application DB Creating a connection is a costly operation, should not be done for each action Real applications: Many users, many actions One connection is not enough Use a pool of connections Wheneer a connection is required, one is supplied from the connection pool 15
Execu.ng SQL statements Statement both static and dynamic SQL statements PreparedStatement semi-static SQL statements Statement stored procedures 16
PreparedStatement class Precompiled, parametrized SQL statements Structure is fixed Values of parameters are determined at run-time 17
PreparedStatement example // initial quantity is always zero String sql = "INSERT INTO Books VALUES('?, 7, '?,?, 0, 7)"; PreparedStatement pstmt = con.preparestatement(sql); // Now instantiate the parameters with alues // Assume that isbn, title, etc. are Jaa ariables that // contain the alues to be inserted pstmt.clearparameters() ; pstmt.setstring(l, isbn); pstmt.setstring(2, title); pstmt.setstring(3, author); pstmt.setfloat(5, price); pstmt.setint(6, year); // Execute the statement int numrows = pstmt.executeupdate(); Fixed structure The statement can be used again, the alues can be changed 18
ResultSets PreparedStatement.executeUpdate only returns the number of affected records PreparedStatement.executeQuery returns data, encapsulated in a ResultSet object (a cursor) ResultSet rs = pstmt.executequery(sql); // rs is now a cursor While (rs.next()) { // the code for processing the data here isbn = rs.getstring(l); title = rs.getstring( TITLE"); } 19
ResultSets A ResultSet is a ery powerful cursor Features: next(): moes one row forward preious(): moes one row back absolute(int num): moes to the row with the specified number relatie (int num): moes forward or backward first() and last() 20
JDBC: Excep.ons and Warnings Most of jaa.sql can throw and SQLException if an error occurs SQLWarning is a subclass of EQLException Not as seere (they are not thrown and their existence has to be explicitly tested) 21
JDBC: Excep.ons and Warnings try { stmt=con.createstatement(); warning=con.getwarnings(); while(warning!= null) { // handle SQLWarnings warning = warning.getnextwarning(): } con.clearwarnings(); stmt.executeupdate(querystring); warning = con.getwarnings(); } //end try catch( SQLException SQLe) { // handle the exception } 22
Database metadata DatabaseMetaData object gies information about the database system and the catalog DatabaseMetaData md = con.getmetadata(); // print information about the drier: System.out.println( Name: + md.getdriername() + ersion: + md.getdrierversion()); 23
Database metadata 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 ResultSet crs = md.getcolumns(null,null,tablename, null); while (crs.next()) { System.out.println( crs.getstring( COLUMN_NAME +, ); } } 24
References and Acknowledgements Most slides are re-used, with minor modification, from: http://pages.cs.wisc.edu/~dbbook/ by Ramakrishnan and Gehrke, and Silberschatz, Korth and Sudarshan: www.db-book.com 25