what is jdbc? java database connectivity (jdbc) is an api for the java programming language that...

59
JDBC

Upload: blake-atkins

Post on 27-Dec-2015

256 views

Category:

Documents


1 download

TRANSCRIPT

  • Slide 1
  • Slide 2
  • What is JDBC? Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database. provides methods for querying and updating data in a database. JDBC has been part of the Java Standard Edition. JDBC classes are contained in the Java package java.sql. JDBC connections support creating and executing statements. These may be update statements such as SQL's CREATE, INSERT, UPDATE and DELETE, or they may be query statements such as SELECT. stored procedures may be invoked through a JDBC connection.
  • Slide 3
  • JDBC Driver Types Type 1 JDBC-ODBC Driver Type 2 Native API Type 3 Net-protocol Type 4 Native-protocol
  • Slide 4
  • Type 1 JDBC-ODBC Driver(1)
  • Slide 5
  • Type 1 JDBC-ODBC Driver(2) The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database. Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source. Client -> JDBC Driver -> ODBC Driver -> Database There is some overhead associated with the translation work to go from JDBC to ODBC.
  • Slide 6
  • Type 1 JDBC-ODBC Driver(3) Advantages Almost any database for which ODBC driver is installed, can be accessed. A type 1 driver is easy to install. Disadvantages Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to the native db connectivity interface. The ODBC driver needs to be installed on the client machine. Considering the client-side software needed, this might not be suitable for applets. Will not be suitable for internet applications.
  • Slide 7
  • Type 2 Native API (1)
  • Slide 8
  • Type 2 Native API (2) The JDBC type 2 driver, also known as the Native-API driver, is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls. The driver is compiled for use with the particular operating system.
  • Slide 9
  • Type 2 Native API (3) Advantages Better performance than Type 1 since no JDBC to ODBC translation is needed. Disadvantages The vendor client library needs to be installed on the client machine. Cannot be used in web-based application due the client side software needed. Not all databases have a client side library
  • Slide 10
  • Type 3 Net-protocol(1)
  • Slide 11
  • Type 3 Net-protocol(2) The JDBC type 3 driver, also known as the Pure Java Driver for Database Middleware, is a database driver implementation which makes use of a middle-tier between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol. the type 3 driver is written entirely in Java. Follows a three tier communication approach. Can interface to multiple databases - Not vendor specific. The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent protocol, and then this net server translates this request into database commands for that database. Client -> JDBC Driver -> Middleware-Net Server -> Any Database
  • Slide 12
  • Type 3 Net-protocol(3) Advantages Since the communication between client and the middleware server is database independent, there is no need for the vendor db library on the client machine. Also the client to middleware need not be changed for a new database. Eg. for the above include jdbc driver features in Weblogic. Can be used in internet since there is no client side software needed. At client side a single driver can handle any database. (It works provided the middlware supports that database!) Disadvantages Requires database-specific coding to be done in the middle tier. An extra layer added may result in a time-bottleneck.
  • Slide 13
  • Type 4 Native-protocol (1)
  • Slide 14
  • Type 4 Native-protocol (2) The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol. The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the Java Virtual Machine of the client. Type 4 drivers are entirely written in Java that communicate directly with a vendor's database, usually through socket connections. The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server. Completely implemented in Java to achieve platform independence. Client Machine -> Native protocol JDBC Driver -> Database server
  • Slide 15
  • Type 4 Native-protocol (3) Advantages These drivers don't translate the requests into an intermediary format (such as ODBC), nor do they need a middleware layer to service requests. Thus the performance may be considerably improved. All aspects of the application to database connection can be managed within the JVM; this can facilitate easier debugging. Disadvantage At client side, a separate driver is needed for each database.
  • Slide 16
  • JDBC API(1) The JDBC API is available in the java.sql and javax.sql packages. Following are important JDBC classes, interfaces and exceptions in the java.sql package: 1.DriverManager-Loads JDBC drivers in memory. Can also be used to open connections to a data source. 2.Connection-Represents a connection with a data source. Is also used for creating Statement, PreparedStatement and CallableStatement objects. 3.Statement-Represents a static SQL statement. Can be used to retrieve ResultSet object/s.
  • Slide 17
  • JDBC API(2) 4.PreparedStatement-Higher performance alternative to Statement object, represents a precompiled SQL statement. 5.CallableStatement-Represents a stored procedure. Can be used to execute stored procedures in a RDBMS which supports them. 6.ResultSet-Represents a database result set generated by using a SELECT SQL statement. 7.SQLException-An exception class which encapsulates database base access errors.
  • Slide 18
  • JDBC steps Load the JDBC driver Define the connection URL Establish the connection Create a Statement object Execute a query or update Process the results Close the connection
  • Slide 19
  • 1.Load the JDBC driver To load a driver, you specify the classname of the database driver in the Class.forName method. By doing so, you automatically create a driver instance and register it with the JDBC driver manager. public static Class forName (StringclassName) throws ClassNotFoundException Example: try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch(ClassNotFoundException e) { }
  • Slide 20
  • 2.Define the connection URL In JDBC, a connection URL specifies the server host, port, and database name with which to establish a connection. Example:String url="jdbc:odbc:test (test is DSN)
  • Slide 21
  • 3. Establish the connection With the connection URL, username, and password, a network connection to the database can be established. Once the connection is established, database queries can be performed until the connection is closed. public static Connection getConnection (Stringurl, Stringuser, Stringpassword) throws SQLException Example for Oracle: Connection connection = DriverManager.getConnection(url, system,manager); Example for Ms Access: Connection connection = DriverManager.getConnection(url, , );
  • Slide 22
  • 4. Create a Statement object Creating a Statement object enables you to send queries and commands to the database. Statement statement = connection.createStatement();
  • Slide 23
  • Execute Query using various execute methods of Statement Interface Following are 3 different execute methods available in Statement Interface: 1.executeQuery( ):public ResultSetexecuteQuery(String sql) throws SQLExceptionUsed with select query 2.executeUpdate( ):public intexecuteUpdate(String sql) throws SQLExceptionUsed with insert, update, delete, alter table etc. 3.execute( ):public booleanexecute(String sql) throws SQLExceptionGenerally used with multiple results are generated. Also used with Create table query.
  • Slide 24
  • 5. Execute a query or update Given a Statement object, you can send SQL statements to the database by using the execute, executeQuery, executeUpdate, or executeBatch methods. String query = "SELECT col1, col2, col3 FROM sometable"; ResultSet resultSet = statement.executeQuery(query);
  • Slide 25
  • 6.Process the results When a database query is executed, a ResultSet is returned. The ResultSet represents a set of rows and columns that you can process by calls to next and various getXxx methods. while(resultSet.next()) { System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + " " + resultSet.getString("firstname") + " " resultSet.getString("lastname")); }
  • Slide 26
  • 7. Close the Connection When you are finished performing queries and processing results, you should close the connection, releasing resources to the database. connection.close();
  • Slide 27
  • The Connection Interface The Connection Interface used to connect to a database is available in the java.sql package. This interface has methods which can be used to prepare statement. This interface also has methods that makes changes to the database permanently or temporary. Method: close() commit() createStatement() isClosed() prepareCall() prepareStatement() rollback()
  • Slide 28
  • The Connection Interface Method(1) close() This method frees the Connection objects database and other JDBC resources. Eg. Connection.close(); commit() This method makes all the changes made since the last commit or rollback permanent. Eg. Connection.commit();
  • Slide 29
  • The Connection Interface Method(2) createStatement() This method creates a statement object for sending SQL statements to the database. Eg. Statement st=Connection.createStatement(); isClosed() This method returns true if the connection is close else returns false. Eg.boolean i=Connection.isClose();
  • Slide 30
  • The Connection Interface Method(3) prepareCall(String s) This method creates a CallableStatement object for calling stored procedures. Eg.CallableStatement cs=Connection.prepareCall(s); prepareStatement(String s) This method creates a PreparedStatement object fo sending SQL statements with or without IN parameter. Eg.PreparedStatement ps=Connection.prepareStatement(s);
  • Slide 31
  • The Connection Interface Method(4) rollback() This method undoes all changes made to the database. Eg.Connection.rollback()
  • Slide 32
  • The Statement Interface Statement: to execute a single query one time. The Statement interface lets you execute a simple SQL statement with no parameters. It executes query immediately without having query compiled. It executes SQL statement that are static & obtain results following their execution. Method: Close() execute() executeQuery() executeUpdate() getMaxRows() getResultSet()
  • Slide 33
  • The Statement Interface Method(1) close() This method releases the statement objects database and JDBC resources. Eg.Statement.close(); execute(String s) Generally used with multiple results are generated. Also used with Create table query. Eg. boolean i=Statement.execute(String sql) throws SQLException
  • Slide 34
  • The Statement Interface Method(2) executeQuery() This method executes the SQL statement specified by s and returns the ResultSet object.Used with select query. Eg.ResultSet rs=Statement.executeQuery(s); executeUpdate() Used with insert, update, delete, alter table etc. Eg.int i=Statement.executeUpdate(s);
  • Slide 35
  • The Statement Interface Method(3) getMaxRows() This method returns the maximum number of rows that are generated by the executeQuery() method. Eg.int i=Statement.getMaxRows(); getResultSet() This method retrives the ResultSet generated by the execute() method. Eg.ResultSet rs=Statement. getResultSet();
  • Slide 36
  • The PreparedStatement Interface Prepared statement: It extends Statement interface which execute a single query multiple times(here the statement will be precompiled and will get better performance) Compiling a query is an overhead that is acceptable if query is called once, however compiling process becomes overhead if query is executed several times. A Prepared Statement object is used when an application plans to reuse a statement multiple times. The application prepares the SQL it plans to use. Once prepared, the application can specify values for parameters in the prepared SQL statement. The statement can be executed multiple times with different parameter values specified for each execution. Another advantage of the Prepared Statement class is the ability to create an incomplete query and supply parameter values at execution time.
  • Slide 37
  • The PreparedStatement Interface A question mark is used as a placeholdar for a value that is inserted into the query after the query is compiled. The prepareStatement() method of the Connection interface is called to return the PreparedStatement object. The setString() method of the PreparedStatement object is used to replace the qustion mark with the value passed to the setString() method. The setString() requires two parameters. First parameter is an integer that identifies the position of the question mark placeholder. second parameter is the value that replaces the question mark placeholder. The query is precompiled once and the setString() method called as needed to change the specified values of the query without having to recompiled the query.
  • Slide 38
  • The PreparedStatement Interface Method(1) Boolean execute() this method execute the SQL statement in this object. The getResult() method is used to retrive the result. ResultSet executeQuery() this method execute the SQL statement in this object. It returns the ResultSet object.
  • Slide 39
  • The PreparedStatement Interface Method(2) int executeUpdate() this method execute the SQL statement in this object. The SQL statement must be an SQL insert,update and delete statement. ResultSetMetaData getMetaData() This method retrives a ResultSetMetaData object that contains information about the columns of the ResultSet object that will be returned when this object is executed.
  • Slide 40
  • ResultSet It contains virtual table consisting of rows and columns. A virtual cursor points to a row of the virtualtable. 2 types of ResultSet Scrollable ResultSet Updatable ResultSet
  • Slide 41
  • How to make ResultSet Scrollable andUpdatable?
  • Slide 42
  • The statement object must be set to handle scrollable and updatable. ResultSet.createStatment(int ResultSetType,int ResultSetConcurrency) ResultSetType-3 Constants TYPE_FORWARD_ONLY TYPE_SCROLL_SENSITIVE TYPE_SCROLL_INSENSITIVE ResultSetConcurrency-2 Constants CONCUR_READ_ONLY CONCUR_UPDATABLE
  • Slide 43
  • TYPE_FORWARD_ONLY It is default setting It restricts the virtual cursor to downward movement. eg:Statement st=con.createStatement();
  • Slide 44
  • TYPE_SCROLL_INSENSITIVE It permits virtual cursor to move in both directions. It makes result set insensitive to the changes made by another J2EE component. Eg:Statement st=con.createStatement(ResultSet.TYPE_SCROLL_INS ENSITIVE,ResultSet.CONUR_UPDATABLE);
  • Slide 45
  • TYPE_SCROLL_SENSITIVE It permits virtual cursor to move in both directions. It makes result set sensitive to the changes made byanother J2EE component. Eg:Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENS ITIVE,ResultSet.CONUR_UPDATABLE);
  • Slide 46
  • CONCUR_READ_ONLY The constant CONCUR_READ_ONLY indicating the concurrency mode for the ResultSet that may not be updated. it mens it is read only READ_ONLY we cant make any changes in ResultSet. Eg. ResultSet.CONCUR_READ_ONLY
  • Slide 47
  • CONCUR_UPDATABLE The constant CONCUR_UPDATABLE indicating the concurrency mode for a ResultSet that may be updated. It permits ResultSet for update operation. Eg. ResultSet.CONCUR_UPDATABLE
  • Slide 48
  • Scrollable ResultSet Until JDBC 2.1 API, the cursor could onlymove down the ResultSet. Six methods to position the cursor first() last() previous() absolute() relative() next() getrow()
  • Slide 49
  • Scrollable ResultSet Method(1) first() Moves to the first row of ResultSet Syntax:public boolean first() Throws SQLException Eg:rs.first() Last() Moves to the last row of ResultSet Syntax:public boolean last() Throws SQLException Eg:rs.last()
  • Slide 50
  • Scrollable ResultSet Method(2) previous() Moves to the previous row of ResultSet Syntax:public boolean previous() Throws SQLException Eg:rs.previous() next() Moves to the next row of ResultSet Syntax:public boolean next() Throws SQLException Eg:rs.next()
  • Slide 51
  • Scrollable ResultSet Method(3) absolute() Moves to the row specified as argument Syntax:public booleanabsolute(introw) Throws SQLException Eg:rs.absolute(2)//moves to 2ndrow relative() Moves to relative number of rows Syntax:public boolean relative(int row) Throws SQLException Eg:rs.relative(3)//moves to 3 forward from current
  • Slide 52
  • Scrollable ResultSet Method(4) getRow() Determines the current row Syntax:public int geRow() Throws SQLException Eg:int n=rs.getRow()
  • Slide 53
  • Updatable ResultSet Updatabilityrefers to the ability to update data in a result set andthen copy the changes to the database The updateXXX() method is used. Syntax:updateXXX(int index, mixed value) It takes 2 parameters 1 st is index or column name 2 nd is the value to be replaced Value updates in the ResultSet only
  • Slide 54
  • Updatable ResultSet Method(1) updateRow() It is called after all the updatexxx() methodsare called. It will update the underline database. Eg:rs.updateInt(1,5); rs.updateString(2,abc); Updates ResultSet rs.updateRow(); //updates database deleteRow() removes a row from result set It removes the current row. Eg:rs.deleteRow() //updates database
  • Slide 55
  • Updatable ResultSet Method(2) insertRow() Inserting a row into the ResultSet is doneusing updateXXX() method. insertRow() method is called afterupdateXXX() method rs.updateInt(1,5); rs.updateString(2,abc); rs.insertRow();//updates database
  • Slide 56
  • CallableStatement Interface The CallableStatement interface is used to call stored procedure from within a J2EE object. A stored procedure is a block of code and is identified by a unique name. The stored procedure is executed by invoking the name of the stored procedure. The CallableStatement interface uses three types of parameters when calling a stored procedure. IN OUT INOUT The IN parameter contains any data that needs to be passed to the stored procedure and whose value is assigned using the setString() method.
  • Slide 57
  • CallableStatement Interface The OUT parameter contains the value returned by the stored procedures. The OUT parameter must be registered using the registerOutParameter() method. The INOUT parameter is a single parameter that is used to both pass information to the stored procedure and retrive information from a stored procedure. The prepareCall() method of the Connection interface is called and is passed the query. This method returns a CallableStatement object. The registerOutParameter() method require two parameters The first parameter is an integer that represents the number of parameter which is -1 meaning the first parameter of the stored procedure. The second parameter to the registerOutParameter() is the datatype of the value returned by the stored procedure.
  • Slide 58
  • CallableStatement Interface The execute() method of the CallableStatement object is called next to execute the query. The execute() method doesnt require the name of the query because the query is already identified when the CallableStatement object is returned by the prepareCall() query method. Create or replace procedure remove (name varchar2) as Begin Delete from emp where emp.Empname=name; End;
  • Slide 59
  • CallableStatement Interface