Java Database Connectivity

29
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University

description

Java Database Connectivity. Vijayan Sugumaran Department of DIS Oakland University. Java Database Connectivity (JDBC). JDBC – provides an interface to Relational Data Sources JDBC library provides the means for executing SQL statements to access and operate on a relational database - PowerPoint PPT Presentation

Transcript of Java Database Connectivity

  • Java Database ConnectivityVijayan SugumaranDepartment of DISOakland University

  • Java Database Connectivity (JDBC)JDBC provides an interface to Relational Data SourcesJDBC library provides the means for executing SQL statements to access and operate on a relational databaseJDBC library is implemented in the java.sql packageSet of classes and interfaces that provide a uniform API for access to broad range of databases

  • Talking to DatabasesA JDBC based application is insulated from the characteristics of specific database enginesJava ApplicationJDBCAccessDatabaseOracleDatabaseSybaseDatabase

  • JDBC ConceptsJDBCs design is very similar to the design of ODBCDriver ManagerLoads database drivers, and manages the connection between the application and the driverDriverTranslates API calls into operations for a specific data sourceConnectionA session between an application and a database

  • JDBC Concepts (contd.)StatementAn SQL Statement to perform a query or update operationMetadataInformation about returned data, the database and the driverResultSetLogical set of columns and rows returned by executing an SQL statement (resulting tuples)

  • Steps during executionThe following steps are executed when running a JDBC applicationImport the necessary classesLoad the JDBC driverIdentify the database sourceAllocate a connection object (create)Allocate a Statement object (create)Execute a query using the Statement objectRetrieve data from the returned ResultSet objectClose the ResultSet objectClose the Statement objectClose the Connection object

  • JDBC Component InteractionDriverManagerConnectionStatementResultSetDriverDatabaseCreatesCreatesCreatesSQLResult(tuples)EstablishLink to DB

  • Steps Involved in Basic JDBC OperationsDriverDriver ManagerConnectionStatementResult Set1. Load the JDBC driver class: Class.forName(driverName);

    2. Open a database connection: DriverManager.getConnection(jdbc:xxx:datasource);

    3. Issue SQL statements: stmt = con.createStatement();stmt.executeQuery (Select * from myTable);

    4. Process result set:while (rs.next()) {name = rs.getString(name);amount = rs.getInt(amt); }Database

  • Two-Tier Database Access ModelJava Application talks directly to the databaseAccomplished through the JDBC driver which sends commands directly to the databaseResults sent back directly to the applicationApplication SpaceJava ApplicationJDBC DriverDatabaseSQLCommandResultSet

  • Three-Tier Database Access ModelJDBC driver sends commands to a middle tier, which in turn sends commands to database.Results are sent back to the middle tier, which communicates them back to the applicationApplication SpaceJava ApplicationJDBC DriverDatabaseSQLCommandResultSetApplication Server(middle-tier)ProprietaryProtocol

  • JDBC Driver TypesJDBC-ODBC Bridge, plus ODBC driver (Type 1)SimplestJDBC methods -> Translate JDBC methods to ODBC methods -> ODBC to native methods -> Native methods APINative-API, partly Java driver (Type 2)JDBC methods -> Map JDBC methods to native methods (calls to vendor library) -> Native methods API (vendor library)JDBC-net, pure Java driver (Type 3)JDBC methods -> Translate to Native API methods through TCP/IP network -> Native API methodsNative-protocol, pure Java driver (Type 4)Java methods -> Native methods in Java

  • Type 1: JDBC-ODBC Bridge, Plus ODBC DriverThis driver type is provided by Sun with JDKProvides JDBC access to databases through ODBC driversODBC driver must be configured for the bridge to workOnly solution if no JDBC driver available for the DBMSApplication SpaceJava ApplicationJDBC ODBC BridgeDatabaseSQLCommandResultSetODBC DriverProprietaryProtocol

  • Type 2: Native-API, Partly Java DriverNative-API driver converts JDBC commands into DBMS-specific native callsSame restrictions as Type1 must have some binary code loaded on its machineDirectly interfaces with the databaseApplication SpaceJava ApplicationType 2 JDBC DriverDatabaseSQLCommandResultSetNative DatabaseLibraryProprietaryProtocol

  • Type 3: JDBC-Net, Pure Java DriverTranslates JDBC calls into a database-independent network protocol and sent to a middleware server.This server translates this DBMS-independent protocol into a DBMS-specific protocol and sent to the databaseResults sent back to the middleware and routed to the clientApplication SpaceJava ApplicationType 3 JDBC DriverDatabaseSQLCommandResultSetMiddleware SpaceProprietaryProtocolJDBC Driver

  • Type 4: Native-Protocol, Pure Java DriverPure Java drivers that communicate directly with the vendors databaseJDBC commands converted to database engines native protocol directlyAdvantage: no additional translation or middleware layerImproves performanceApplication SpaceJava ApplicationType 4 JDBC DriverDatabaseSQL Command Using Proprietary ProtocolResult Set Using Proprietary Protocol

  • Driver ManagerThe DriverManager class is responsible for establishing connections to the data sources, accessed through the JDBC driversJDBC database drivers are defined by classes that implement the Driver interfaceThe Properties class defined in java.util package defines/stores the property (key) and the corresponding value (object)You can use the setProperty method to set the value of any of the propertiesE.g: System.setProperty(jdbc.drivers, sun.jdbc.odbc.JdbcOdbcDriver)The first is the key (or name) for the property to be set and the second argument is the value to be set

  • Driver Manager (contd)If a security manager is in effect, may not be able to set the System property then setProperty() will throw an exception of type Security ExceptionIf not able to set System property, the driver can be loaded explicitly by calling the static method forName in the Class class and pass the driver argumentEg: Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);The forName() method can throw a ClassNotFoundException if the driver class is not found. Hence, this function call should be in a try-catch blockThe above statement loads the JDBC driver and takes care of any initialization that needs to be done

  • Connection ObjectCreating a connection to a data sourceConnection object represents an established connection to a particular data sourceA connection object can also be used to query the data source (data and meta data)Different versions of getConnection() method contained in the DriverManager class that returns a connection object:Connection myconn = DriverManager.getConnection(source);Connection myconn = DriverManager.getConnection(source, username, password);Example

    String mysource = jdbc:odbc:technical_library;Connection myconn = DriverManager.getConnection(mysource); System DSN name ODBC data source

  • DSN-less ConnectionMaking a connection to the database without having to specify the DSN variable at the system levelExplicitly specify a connection stringShould be exactly the same as shown below except the name of the database and its path

    String source = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=movies_vj.mdb"; con = DriverManager.getConnection(source);Database name, should be in the same directory as the classCan also specify absolute path

  • Statement ObjectProvides workspace for creating an SQL query, execute it, and retrieve the results that are returnedStatement objects are created by calling the createStatement() method of a valid connection objectUsed to execute an SQL query by calling the executeQuery() method of Statement objectThe SQL query string is passed as argument to the executeQuery() methodThe result of executing the query is returned as on object of type ResultSet

    JDBC Provides two other kinds of objects to execute SQL statement:PreparedStatement -> extends Statement classCallableStatement -> extends PreparedStatement class

    Statement mystatement = myconn.createStatement();ResultSet myresults = mystatement.executeQuery(select * from authors);

  • ResultSet ObjectThe results of executing an SQL query are returned in the form of an object that implements the ResultSet interfaceResultSet object contains a cursor that points to a particular record (called the current record)When the ResultSet object is created, the cursor points to the position immediately preceeding the first recordSeveral methods available to navigate the ResultSet by moving the cursorfirst(), last(), beforeFirst(), afterLast(), next(), previous(), etc. //returns true if the move is successfulisFirst() //whether you reached the beginning of the ResultSetisLast() // whether you reached the end of the ResultSet

  • Accessing Data in a ResultSetWe can retrieve the value of any column for the current row (specified by the cursor) by name or positionUsing Name: authorNames.getString(lastname);

    Using Position: authorNames.getString(2);

    Using the column position is a little bit fasterMethods for Retrieving Column DatagetString(), getInt(), getShort(), getFloat(), getDouble(), getTime() etc. We can always use getString() method for numerical values if we are not going to do some computationsColumn names are NOT case sensitiveResultSetMetaData object has metadata information about records, I.e., column names, data types etc.

    Name of theResultSetMethod that returnsthe value of StringName of the column or attributeSecond column in the row or tuple

  • Getting MetaData for a ResultSetThe ResultSetMetaData object encapsulates the metadata for a ResultSet objectUse getMetaData() method of ResultSet object to get the metadataSome of the methods of ResultSetMetaData object:getColumnName() // returns column namegetColumnType() // returns column data typegetColumnCount() // # of columns in the rowgetTableName() //returns the name of the tablegetColumnLabel() //suggested label for a column for use in printoutsThe Types class in java.sql package contains the field types used in SQLEg: CHAR, VARCHAR, DOUBLE, INT, TIME etc.Once we know the SQL data type, then we can call the appropriate getXXX() function for getting the value of that column

  • Scrollable Result SetsIn JDBC1.0, result sets could be navigated in only one direction (forward) and starting at only one point (first row)Since JDBC 2.0, the cursor can be manipulated as if it were a array indexMethods exist for reading both forward and backward, for starting from any row, and for testing the current cursor location.

  • JDBC 2.0 Navigation Methods for Scrollable Result Setsboolean next ( ) Advances the cursor to the next row.boolean previous ( ) Moves the cursor back one row.boolean first ( ) Moves the cursor to the first row.boolean last ( ) Moves the cursor to the last row. void beforeFirst ( ) Moves the cursor before the first row, usually in anticipation of calling next ( )void afterLast ( ) Moves the cursor after the last row, usually in anticipation of calling previous ( )boolean Moves the cursor to the specifiedabsolute (int row) row. Specifying a negative number moves the cursor relative to the end of the result set;

  • JDBC 2.0 Navigation Methods for Scrollable Result Sets (contd.)

    boolean Moves the cursor forward orrelative (int row) backward the number of rows specified. boolean True if the cursor is before the isBeforeFirst ( ) first row.boolean True if the cursor is after theisAfterLast ( ) last row. boolean isFirst ( ) True if the cursor is positioned on the first row.boolean isLast ( ) True if the cursor is positioned on the last row.

  • Creating Scrollable Result SetsStatement object created with parameters to indicate specific capabilitiesConnection.createStatement() method can have up to three parameters:resultSetType type of scrolling to be usedresultSetConcurrency indicates whether the result set can be updatedresultSetHoldability specifies whether to close cursors when a commit is doneExamplestmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

  • Constants in Result SetsCursor Related ConstantsTYPE_FORWARD_ONLYJDBC 1.0-style navigation in which the cursor starts at the first row and can only move forward.TYPE_SCROLL_INSENSITIVEAll cursor positioning methods are enabled; the result set doesnt reflect changes made by others in the underlying table.TYPE_SCROLL_SENSITIVEAll cursor positioning methods are enabled the result set reflects changes made by others in the underlying table.

  • Constants in Result Sets (contd.)Updating Record SetsCONCUR_READ_ONLYThe results set wont be updatableCONCUR_UPDATABLERows can be added and deleted, and columns can be updated. Closing CursorsHOLD_CURSORS_OVER_COMMITDo not close cursors after a commit is done. CLOSE_COURSORS_AT_COMMITClose cursors when a commit is done.