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.

Slides:



Advertisements
Similar presentations
Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Advertisements

1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
Objectives Describe JDBC Describe JDBC Driver Types
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Accessing Databases with JDBC. Introduction to JDBC JDBC provides a standard library for accessing databases by using the JDBC API. JDBC standardizes.
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Think Possibility Integrating Web Applications With Databases.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
CSE470 Software Engineering Fall Database Access through Java.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 38 Advanced Java Database.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
CONTROLPANEL Java.sql package This package provides the APIs for accessing and processing data which is stored in the database especially relational.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
JDBC – Java DataBase Connectivity. JDBC API Overview JDBC is Java API that allows the Java programmers to access database management system from Java.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
JDBC Session 2 Tonight’s topics: 1.Prepared Statements 2.Transaction Processing 3.Callable Statements & Stored Procedures 4.Scrollable & Updatable Result.
JDBC – Java Database Concentricity
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
Chapter 17 Accessing Databases with JDBC. JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Session 30 Basics of JDBC. Java Simplified / Session 30 / 2 of 33 Review A Swing menu consists of a menubar, menuitems and menus. Trees are used to depict.
JDBC CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
JDBC
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
UNIT III - JDBC JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database Results, handling database Queries. Networking–
1 Session 2 Module 3: Scrollable Resultset and Rowsets.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC Session 14.
JDBC (Java Database Connectivity)
JDBC Chapter 1 JDBC Introduction
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Chapter 7 Chapter 7 Java Database Connectivity using JSP 1 (IS 203) WebProgramming (IS 203) Web Programming.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_Oracle10g_JDBC 1 Application Development (JDBC)
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
JDBC.
DEPTT. OF COMP. SC & APPLICATIONS
Note: To complete the examples in this section you need access to a database!! Most of the examples work for any database with JDBC drivers. However, connecting.
Interacting with Database
ODBC, OCCI and JDBC overview
JDBC Database Management Database connectivity
Web Technologies IT230 Dr Mohamed Habib.
Introduction to Programming with Java
Chapter 16 JAVA DATABASE CONNECTIVITY
Objectives In this lesson, you will learn about:
Mr. Harish Sharma Asst. Professor Dept. of CA & IT SGRRITS Dehradun
Interacting with Database
Presentation transcript:

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.

JDBC Driver Types Type 1 JDBC-ODBC Driver Type 2 Native API Type 3 Net-protocol Type 4 Native-protocol

Type 1 JDBC-ODBC Driver(1)

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.

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.

Type 2 Native API (1)

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.

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

Type 3 Net-protocol(1)

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

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.

Type 4 Native-protocol (1)

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

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.

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.

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.

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

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) { }

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)

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, “ ”,” ”);

4. Create a Statement object Creating a Statement object enables you to send queries and commands to the database. Statement statement = connection.createStatement();

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.

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);

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")); }

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();

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()

The Connection Interface Method(1) close() This method frees the Connection object’s 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();

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();

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);

The Connection Interface Method(4) rollback() This method undoes all changes made to the database. Eg.Connection.rollback()

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()

The Statement Interface Method(1) close() This method releases the statement object’s 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

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);

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();

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.

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.

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.

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.

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

How to make ResultSet Scrollable andUpdatable?

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

TYPE_FORWARD_ONLY It is default setting It restricts the virtual cursor to downward movement. eg:Statement st=con.createStatement();

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);

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);

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 can’t make any changes in ResultSet. Eg. ResultSet.CONCUR_READ_ONLY

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

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()

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()

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()

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

Scrollable ResultSet Method(4) getRow() Determines the current row Syntax:public int geRow() Throws SQLException Eg:int n=rs.getRow()

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

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

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

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.

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.

CallableStatement Interface The execute() method of the CallableStatement object is called next to execute the query. The execute() method doesn’t 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;

CallableStatement Interface