“Enterprise” Java l Group of APIs (class libraries) intended to facilitate large scale business applications, primarily database related applications – JDBC Java DataBase Connectivity – RMI Remote Method Invocation – Java IDL Interface Definition Language (Corba compliance) – JNDI Directory and naming services – ... Java for client/server development Advantages: l Platform independence – – l No installation needed on client machine Business solution for client/server development like Visual Basic, Delphi or Power Builder are not well suited to Internet development because they are platform dependent No pointers – l Java G - 1 Easy to refer to data without using pointers Local computation Constraints: l User Security l Make Applets trustworthy l Performance considerations Java G - 2 What is JDBC? Java G - 3 JDBC (Java DataBase Connectivity) is l an intermediary program between the Java application (or, possibly, Applet) and a database. – classes and interfaces written in Java l an API for executing SQL statements – easy to send SQL statements to any relational database With Java and the JDBC API you can write applications that are independent of: l Platform – l all employees access databases on company intranet from mix of Macs, PCs, & Unix workstations Database product – have a web page with applet that uses information obtained from a remote databases of any type. JDBC Architecture Java G - 4 JDBC API JDBC Driver API Open Standard - In order to pass JDBC compliance tests, a driver must support at least ANSI SQL92 Entry Level standard Types of JDBC Drivers l JDBC Net Driver (all-Java driver) - Translates JDBC calls into a DBMS-independent net protocol which is then translated to a particular DBMS protocol by a server. l JDBC-ODBC bridge (mixed Java and binary, written in C) l JDBC to Native-API (partly-Java driver, partly in C) JDBC and ODBC l ODBC is a form of “C” function library, providing functions and data structures used to pass SQL requests to chosen database driver JDBC can act as a Java language, object based interface to ODBC (useful if have ODBC installed and compatible drivers already implemented) – l Java G - 6 When JavaSoft started development of database facilities, there was already one fairly general package for interfacing to databases - Microsoft’s ODBC (Open DataBase Connectivity Package). – l Java G - 5 JDBC is simpler and doesn’t use pointers lie ODBC If database developer can supply appropriate Java compatible “driver” modules, can leave out ODBC. The JDBC - ODBC Bridge l Java G - 7 The JDBC-ODBC bridge provides JDBC access via most ODBC drivers. – – ODBC binary code and database client code must be loaded on each client machine Appropriate for use on a corporate intranet, or for Java server in a 3-tier system Three-tier Applet or Application l l Three-tier access to databases may be used, make calls to a "middle tier" of services on the net whose implementations in turn access databases. These calls might be made through RPC (remote procedure call) or through an ORB (object request broker) • More secure • Less load on DBMS server Java G - 8 Java G - 9 To use JDBC ... l l l Need appropriate software installed on system. But, provided low level manager and driver is in place, programmers can ignore details of drivers, JDBC/ODBC bridges etc. Programming done using instances of various high level classes that allow an application programmer to – 1. open connections to particular databases (DriverManager and Connection) – 2. execute SQL statements (Statement) – 3. process the results (ResultSet) The JDBC API l The most important interfaces in JDBC API are: – – – DriverManager which handles loading of drivers and provides support for creating new database connections Connection which represents a connection to a particular database Statement which acts as a container for executing a SQL statement on a given connection ResultSet which controls access to the row results of a given statement The Statement interface has two important sub-types: – l – CallableStatement for executing a call to a database stored procedure All of these interfaces are available from the java.sql package – l PreparedStatement for executing a pre-compiled SQL statement Java G - 10 DriverManager l Java G - 11 Keeps track of available drivers. Drivers have to be loaded and registered with the DriverManager – – 1. Automatic: Run-time system uses a list of available drivers defined in an environment variable 2. By explicitly loading code for and creating a driver using Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); l Handles establishment of connection between a database and the appropriate driver. Opening a connection l To interact with the database, we need a Connection – l Java G - 12 Returned by the getConnection() method Ex: Connecting to a data source String user = ”Fred”; String pass = ”Wilma”; Connection con = DriverManager.getConnection (dBName, user, pass); l the getConnection() method is overloaded getConnection (String dbName ); getConnection (String dbName , String user, String pass); getConnection (String dbName , Properties info); What’s in a Database Name (JDBC URL) l The database is specified with a JDBC URL, an extended URL-address (similar to a webb-address) l Ex: l Form: jdbc:<subprotocol>:<subname> l 1. “jdbc” is the protocol (compare with http) l 2. subprotocol is associated with specific driver l 3. rest of a JDBC URL: subname defines the datasource jdbc:Sybase://datan.du.se:3306/java?user=java – name of local database or internet style machine.domain name and port – possibly parameters specific to particular form of database connection – optionally including login name and user password Sending SQL statements - executeQuery l Once a connection is made to a database, you can start sending SQL statements to it – – l Java G - 13 1. Use the Connection. createStatement method to obtain a Statement object 2. Execute method executeQuery (or executeUpdate ) For example, to select all columns of data from a table called MyTable we execute method executeQuery : ResultSet = rs; Statement stmt; stmt = con. createStatement (); rs = stmt.executeQuery(“SELECT * FROM MyTable”); Java G - 14 Sending SQL statements - executeUpdate l Java G - 15 For example, to create a table called Data with one row of data, use the following: // create table with name and height columns Statement stmt; stmt = con. createStatement (); stmt.executeUpdate( "CREATE TABLE Data (name varchar (32), height integer);"); stmt.executeUpdate( "INSERT INTO Data VALUES ('John', 68);"); con.close(); // close connection, committing transaction ResultSet l l ResultSet provides access to a table of data generated by executing a query. For example, the following code fragment selects two columns of data from a table called MyTable in ascending height order: ResultSet rs = stmt. executeQuery ( "SELECT name, height FROM MyTable ORDER BY height ASC;"); l The rows of resulting data must be read in order retrieved. – Within a row its column values can be accessed in any order. Java G - 16 ResultSet Navigation l ResultSet objects maintain a cursor to data. l – The cursor is initially positioned before the first row The next() method: – moves the cursor to the next row of the ResultSet – returns false when cursor is at the end of the ResultSet Java G - 17 while (rs.next()) { name = rs.getString("name"); height = rs.getInt("height"); System.out. println (name + ":" + height); } Reading Data Values l l There is a getXXX method for each of the major data types. JDBC attempts to convert the data – getString (...) returns data as a string – getInt (...) returns data as an int The column to read is identified by name or index (starting from 1) – rs.getInt(”height”) – more readable – less efficient – myRS.getInt(1) – more efficient – more obscure Java G - 18 Full JDBC: Basic example try Java G - 19 { Class.forName("my.sql.Driver"); Connection con = DriverManger .getConnection(db_url, user, pass); Statement stmt = con. createStatement(); ResultSet rs = stmt.executeQuery ( ”SELECT Name, Address FROM MyTable”); while(rs.next()) { System.out. println(rs.getString(1)); } catch ( SQLException e) { System.err. println(”An error occurred: ” + e); } Prepared Statements l l l When performing the same operation multiple times, use a PreparedStatement that can take one or more parameters as input arguments Prepared Statements are: – created using the prepareStatement() method – executed using the executeStatement() method The prepareStatement() is precompiled by the SQL engine for runtime efficiency Java G - 20 Creating and Using Prepared Statements l Java G - 21 Creating a PreparedStatement object for a table called Data with two columns: PreparedStatement ps ; ps = con.prepareStatement ("INSERT INTO Data VALUES (?, ?)"); – – The parameters, indicated by '?', can be filled in by setXXX methods. Parameters are referred to sequentially, by number. The first parameter is 1 For example, name of type varchar and height of type integer the parameters to prep can be set via: ps.setString(1, "Jim"); ps.setInt(2, 70); l Using a prepared statement: Resultset rs = ps.executQuery(); – executeQuery, executeUpdate and execute are redefined for Prepared Statements (no parameters) Java G - 22 Java-SQL Type Equivalence l l For each getXXX method, the JDBC driver must convert between the database data type and a Java equivalent--the driver will not let you perform an invalid data conversion (for example, String to integer), but will let you get everything as a String. Java method SQL Type getInt INTEGER getLong BIG INT getFloat REAL getDouble FLOAT getBignum DECIMAL getBoolean BIT The common conversions are shown in the table getString VARCHAR getString CHAR getDate DATE getTime TIME getTimestamp TIME STAMP getObject any type Stored Procedures l Java G - 23 A stored procedure is a block of SQL code stored in the database and executed on the server. The interface allows you to interact with them. (Similar to working with PreparedStatements ) Stored procedures can also have parameters that receives information from a stored procedure. First you create a CallableStatement object and prepare it with the required stored procedure: – l CallableStatement cstmt = con.prepareCall ( "{call getDailyTotal (?, ?)}"); cstmt.setString(1, "Mon"); cstmt.registerOutParameter (2,java.sql.Types.INTEGER); l Whenever required the stored procedure is fired with: cstmt.executeUpdate(); System.out.println ("Total is " + cstmt.getInt(2)); Transaction Management l A transaction is a set of statements that have been executed and committed or rolled back. – – l l Java G - 24 To commit a transaction, call the method commit on the appropriate connection; Use the rollback to remove all changes since the last commit By default, all new connections are in auto-commit mode, which means that each "execute" is a complete transaction. Call Connection.setAutoCommit to change the default. Any locks held by a transaction are released upon the method commit. Connection con = DriverManager .getConnection(...); con.setAutoCommit (false); Statement s = con. createStatement(); s.executeUpdate("SQL statement 1 "); s.executeUpdate("SQL statement 2 "); s.executeUpdate("SQL statement 3 "); con.commit();// transaction (3 stmnts) committed here JDBC Exceptions l JDBC provides three types of exceptions: l SQLException – l The SQLException is the basis of all JDBC exceptions. It consists of three pieces of information, a String message, like all children of Exception, another String containing the XOPEN SQL state (as described by specification), and a driver/source specific int for an additional error code. SQLWarning – l The SQLWarning class is similar to SQLException, however it is considered a noncritical error and is not thrown. It is up to the programmer to poll for SQLWarning messages through the getWarnings methods of Connection, ResultSet, and Statement. DataTruncation – The DataTruncation class is a special type of SQLWarning. It is reported with other SQLWarning instances and indicates when information is lost during a read or write operation Metadata l l Java G - 25 The DatabaseMetaData class provides information about the database as a whole. After connecting to the database, you can fetch the database metadata through the Connection.getMetaData method. This returns an instance of Metadata, which has around 100 methods to discover information about the database such as. getTables () getColumns () getProcedures () getProcedureColumns () getTableTypes , getTablePrivileges , getCatalogs etc getStringFunctions , getSystemFunctions , getTimeDateFunctions etc Java G - 26