Objectives In this lesson, you will learn about:

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 JDBC Java Database Connectivity. 2 c.pdf
Java Database Connectivity JDBC ICW Lecture 12 Errol Thompson.
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.
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Introduction to JDBC (Java Database Connectivity).
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.
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.
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.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
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.
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.
Java Utility Classes CS 21b. Some Java Utility Classes Vector Hashtable StringTokenizer * import java.util.*;
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.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui COMP 302 Database Systems Java Data Base Connectivity Lecturer Dr Pavle Mogin.
Introduction to JDBC Michelle Lee, Ye Wu & Jeff Offutt SWE 432 Design and Implementation of Software for the Web.
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. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
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.
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.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
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.
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.
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.
Basics of JDBC Session 14.
JDBC - Resultset The java.sql.ResultSet interface represents the result set of a database query. A ResultSet object maintains a cursor that points to the.
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.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
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
Lec - 14.
JDBC Database Management Database connectivity
JDBC – Java Database Connectivity
Part 4 FaaDoOEngineers.com IBM.
Introduction to Programming with Java
Chapter 16 JAVA DATABASE CONNECTIVITY
Design and Implementation of Software for the Web
Mr. Harish Sharma Asst. Professor Dept. of CA & IT SGRRITS Dehradun
Interacting with Database
JDBC – ODBC DRIVERS.
JAVA DATABaSE CONNECTIVITY
JDBC Example.
Presentation transcript:

Objectives In this lesson, you will learn about: Layers in JDBC architecture Types of JDBC drivers Classes and interfaces of JDBC API Steps to create JDBC applications JDBC and JavaBeans

Database Connectivity Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases. The following figure shows the Airline Reservation System developed in Java interacting with the Airlines database using the JDBC API: JDBC and JavaBeans

Database Connectivity (Contd.) JDBC Architecture: Provides the mechanism to translate Java statements into SQL statements. Can be classified into two layers: JDBC application layer JDBC driver layer JDBC and JavaBeans

Database Connectivity (Contd.) JDBC Drivers: Convert SQL statements into a form that a particular database can interpret. Retrieve the result of SQL statements and convert the result into equivalent JDBC API class objects. Are of four types: JDBC-ODBC Bridge driver Native-API Partly-Java driver JDBC-Net Pure-Java driver Native Protocol Pure-Java driver JDBC and JavaBeans

Database Connectivity (Contd.) JDBC-ODBC Bridge driver JDBC and JavaBeans

Database Connectivity (Contd.) Native-API Partly-Java driver JDBC and JavaBeans

Database Connectivity (Contd.) JDBC-Net Pure-Java driver JDBC and JavaBeans

Database Connectivity (Contd.) Native-Protocol Pure-Java driver JDBC and JavaBeans

Using JDBC API The JDBC API classes and interfaces are available in the java.sql and the javax.sql packages. The commonly used classes and interfaces in the JDBC API are: DriverManager class: Loads the driver for a database. Driver interface: Represents a database driver. All JDBC driver classes must implement the Driver interface. Connection interface: Enables you to establish a connection between a Java application and a database. Statement interface: Enables you to execute SQL statements. ResultSet interface: Represents the information retrieved from a database. SQLException class: Provides information about the exceptions that occur while interacting with databases. JDBC and JavaBeans

Using JDBC API (Contd.) The steps to create JDBC application are: Load a driver Connect to a database Create and execute JDBC statements Handle SQL exceptions JDBC and JavaBeans

Using JDBC API (Contd.) Loading a Driver Programmatically: Using the forName() method Using the registerDriver()method Manually: By setting system property JDBC and JavaBeans

Using JDBC API (Contd.) Using the forName() method The forName() method is available in the java.lang.Class class. The forName() method loads the JDBC driver and registers the driver with the driver manager. The method call to use the the forName() method is: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); JDBC and JavaBeans

Using JDBC API (Contd.) Using the registerDriver()method You can create an instance of the Driver class to load a JDBC driver. This instance enables you to provide the name of the driver class at run time. The statement to create an instance of the Driver class is: Driver d = new sun.jdbc.odbc.JdbcOdbcDriver(); You need to call the registerDriver() method to register the Driver object with the DriverManager. The method call to register the JDBC-ODBC Bridge driver is: DriverManager.registerDriver(d); JDBC and JavaBeans

Using JDBC API (Contd.) Setting System Property Add the driver name to the jdbc.drivers system property to load a JDBC driver. Use the –D command line option to set the system property on the command line. The command to set the system property is: java –Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver SampleApplication JDBC and JavaBeans

Using JDBC API (Contd.) Connecting to a Database The DriverManager class provides the getConnection() method to create a Connection object. The getConnection()method method has the following three forms: Connection getConnection (String <url>) Connection getConnection (String <url>, String <username>, String <password>) Connection getConnection (String <url>,Properties <properties>) JDBC and JavaBeans

Using JDBC API (Contd.) Creating and Executing JDBC Statements The Connection object provides the createStatement() method to create a Statement object. You can use static SQL statements to send requests to a database to retrieve results. The Statement interface contains the following methods to send static SQL statements to a database: ResultSet executeQuery(String str) int executeUpdate(String str) boolean execute(String str) JDBC and JavaBeans

Using JDBC API (Contd.) Various database operations that you can perform using a Java application are: Querying a table Inserting rows in a table Updating rows in a table Deleting rows from a table Creating a table Altering and dropping a table JDBC and JavaBeans

Using JDBC API (Contd.) Querying a Table The SELECT statement is executed using the executeQuery() method and returns the output in the form of a ResultSet object. The code snippet to retrieve data from the authors table is: String str = "SELECT * FROM authors"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(str); JDBC and JavaBeans

Using JDBC API (Contd.) Inserting Rows in a Table The executeUpdate() method enables you to add rows in a table. The code snippet to insert a row in the authors table is: String str = "INSERT INTO authors (au_id, au_lname, au_fname, address, city, state, contract) VALUES ('998-72-3568', 'Ringer','Albert','801 826-0752 67 Seventh Av.', 'Salt Lake City','UT','1')"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); JDBC and JavaBeans

Using JDBC API (Contd.) Updating Rows in a Table The code snippet to modify a row in the authors table is: String str = "UPDATE authors SET address='10932 Second Av.’ WHERE au_id='998-72-3568'"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); Deleting Rows from a Table The code snippet to delete a row from the authors table is: String str = "DELETE FROM authors WHERE au_id='998-72-3568'"; JDBC and JavaBeans

Using JDBC API (Contd.) Creating a Table The CREATE TABLE statement is used to create and define the structure of a table in a database. The code snippet to create a table is: String str="CREATE TABLE MyProduct" +" (p_id INTEGER," +"p_name VARCHAR(25)," +"rate FLOAT," +"unit_msr CHAR(6))"; Statement stmt=con.createStatement(); stmt.execute(str); JDBC and JavaBeans

Using JDBC API (Contd.) Altering and Dropping a Table DDL provides the ALTER statement to modify the definition of database object. The code snippet to add a column to the MyProduct table is: String str="ALTER TABLE MyProduct " +"ADD quantity INTEGER"; Statement stmt=con.createStatement(); stmt.execute(str); DDL provides the DROP TABLE statement to drop a table from a database. The code snippet to drop the MyProduct table from a database is: String str="DROP TABLE MyProduct"; JDBC and JavaBeans

Using JDBC API (Contd.) Handling SQL Exceptions The java.sql package provides the SQLException class, which is derived from the java.lang.Exception class. You can catch the SQLException in a Java application using the try and catch exception handling block. The SQLException class contains various methods that provide error information, these methods are: int getErrorCode(): Returns the error code associated with the error occurred. String getSQLState(): Returns X/Open error code. SQLException getNextException(): Returns the next exception in the chain of exceptions. JDBC and JavaBeans

Accessing Result Sets A ResultSet object maintains a cursor that enables you to move through the rows stored in a ResultSet object. Types of Result Sets The various types of ResultSet objects to store the output returned by a database are: Read only: Allows you to only read the rows in a ResultSet object. Forward only: Moves the result set cursor from first row to last row in forward direction only. Scrollable: Moves the result set cursor forward or backward through the result set. Updatable: Allows you to update the result set rows retrieved from a database table. JDBC and JavaBeans

Accessing Result Sets (Contd.) The following table lists various fields of ResultSet interface that you can use to specify the type of a ResultSet object: ResultSet Fields Description TYPE_SCROLL_SENTITIVE Specifies that the cursor of the ResultSet object is scrollable and it reflects the changes in the data made by other users. TYPE_SCROLL_INSENSITIVE Specifies that the cursor of the ResultSet object is scrollable and it does not reflect changes in the data made by other users. TYPE_FORWARD_ONLY Specifies that the cursor of the ResultSet object moves in forward direction only from the first row to the last row. JDBC and JavaBeans

Accessing Result Sets (Contd.) The following table lists various fields of the ResultSet interface that you can use to specify different concurrency modes of result sets: ResultSet Fields Description CONCUR_READ_ONLY Specifies the concurrency mode that does not allow you to update the ResultSet object. CONCUR_UPDATABLE Specifies the concurrency mode that allows you to update the ResultSet object. JDBC and JavaBeans

Accessing Result Sets (Contd.) The following table lists various fields of the ResultSet interface that you can use to specify different cursor states of result sets: ResultSet Fields Description HOLD_CURSORS_OVER_COMMIT Specifies that a ResultSet object should not be closed after data is committed to the database. CLOSE_CURSORS_AT_COMMIT Specifies that a ResultSet object should be closed after data is committed to the database. JDBC and JavaBeans

Accessing Result Sets (Contd.) The createStatement() method has the following three overloaded forms: Statement createStatement() Statement createStatement(int, int) Statement createStatement(int, int, int) JDBC and JavaBeans

Accessing Result Sets (Contd.) The following tables lists the methods of ResultSet interface: Method Description boolean first() Shifts the control of a result set cursor to the first row of the result set. boolean isFirst() Determines whether the result set cursor points to the first row of the result set. boolean beforeFirst() Shifts the control of a result set cursor before the first row of the result set. boolean isBeforeFirst() Determines whether the result set cursor points before the first row of the result set. boolean last() Shifts the control of a result set cursor to the last row of the result set. boolean isLast() Determines whether the result set cursor points to the last row of the result set. JDBC and JavaBeans

Accessing Result Sets (Contd.) The methods of ResultSet interface (Contd.) Method Description boolean afterLast() Shifts the control of a result set cursor after the last row of the result set. boolean isAfterLast() Determines whether the result set cursor points after the last row of the result set. boolean previous() Shifts the control of a result set cursor to the previous row of the result set. boolean absolute(int i) Shifts the control of a result set cursor to the row number that you specify as a parameter. boolean relative(int i) Shifts the control of a result set cursor, forward or backward, relative to the row number that you specify as a parameter. JDBC and JavaBeans

Accessing Result Sets (Contd.) JDBC allows you to create an updatable result set that enables you to modify the rows in the result set. The following table lists some of the methods used with updatable result set: Method Description void updateRow() Updates a row of the current ResultSet object and the underlying database table. void insertRow() Inserts a row in the current ResultSet object and the underlying database table. void deleteRow() Deletes a row from the current ResultSet object and the underlying database table. void updateString() Updates the specified column with the given string value. void updateInt() Updates the specified column with the given int value. JDBC and JavaBeans

Demonstration-Creating a JDBC Application to Query a Database Problem Statement Create an application to retrieve information (author id, name, address, city, and state) about the authors who are living in the city where the city name begins with the letter “O”. JDBC and JavaBeans

Demonstration-Creating a JDBC Application to Query a Database (Contd.) Solution JDBC-ODBC Bridge driver is to be used for creating the application. To solve the above problem, perform the following tasks: Create a Data Source Name (DSN). Code the application. Compile and execute the application. JDBC and JavaBeans

Summary In this lesson, you learned: JDBC Architecture consists of two layers: JDBC application layer: Signifies a Java application that uses the JDBC API to interact with the JDBC driver manager. JDBC driver layer: Contains a driver, such as an SQL Server driver, which enables a Java application to connect to a database. This layer acts as an interface between a Java application and a database. The JDBC driver manager manages various JDBC drivers. The JDBC driver is software that a Java application uses to access a database. JDBC and JavaBeans

Summary (Contd.) JDBC supports four types of drivers: JDBC-ODBC Bridge driver Native-API Partly-Java driver JDBC-Net Pure-Java driver Native Protocol Pure-Java driver The JDBC API consists of various classes and interfaces that enable Java applications to interact with databases. The classes and interfaces of the JDBC API are defined in the java.sql and javax.sql packages. You can load a driver and register it with the driver manager either programmatically or manually. Two ways to load and register a driver programmatically are: Using the Class.forName() method Using the registerDriver() method JDBC and JavaBeans

Summary (Contd.) You can add the driver name to the jdbc.drivers system property to load and register a JDBC driver manually. A Connection object establishes a connection between a Java application and a database. A Statement object sends requests to and retrieves results from a database. You can insert, update, and delete data from a table using the DML statements in Java applications. You can create, alter, and drop tables from a database using the DDL statements in Java applications. A ResultSet object stores the result retrieved from a database when a SELECT statement is executed. You can create various types of ResultSet objects such as read only, updatable, and forward only. JDBC and JavaBeans