Professional Documents
Culture Documents
INTRODUCING JDBC
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
1A.1
Introducing JDBC
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
NIIT
Lesson 1A / Slide 1 of 36
INSTRUCTOR NOTES
Lesson Overview
This lesson will help the students to become familiar with JDBC concepts. The students will learn to create Java applications that can access and modify the information stored in databases. Your highlight points during this session should be: JDBC architecture Types of database drivers Interfaces and classes in the java.sql package Creating and working with database tables Types of result sets
1A.2
Setup Requirements
Ensure the following before conducting the session: SQL Server 2000, Windows 2003 Server, J2SDK 1.4.2 are installed on the faculty node. You have copied the following data files from \Data Files For Faculty\01_JDBC and JavaBeans\Lesson 1A-1 folder: AuthorsInfo.java
1A.3
DATABASE CONNECTIVITY
Introducing JDBC
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:
NIIT
Lesson 1A / Slide 2 of 36
1A.4
Introducing JDBC
JDBC Architecture: Provides the mechanism to translate Java statements into SQL statements. Can be classified into two layers: JDBC application layer JDBC driver layer
NIIT
Lesson 1A / Slide 3 of 36
1A.5
Introducing JDBC
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
NIIT
Lesson 1A / Slide 4 of 36
1A.6
Introducing JDBC
NIIT
Lesson 1A / Slide 5 of 36
1A.7
Introducing JDBC
NIIT
Lesson 1A / Slide 6 of 36
1A.8
Introducing JDBC
NIIT
Lesson 1A / Slide 7 of 36
1A.9
Introducing JDBC
NIIT
Lesson 1A / Slide 8 of 36
INSTRUCTOR NOTES
You can start the session by asking the students about database, DBMS, and RDBMS. You can also ask the students about the feasibility of using RDBMS for doing data entry or modifying the data. You can further probe them as to how should one do data entry.
Additional Input
Database Concepts: Database is a collection of related information stored in an organized form on a computer such as computerized library system. Databases are managed by Database Management System (DBMS), which is software that enables you to access, store, modify, and delete information. Each database stores information in a table, which consists of rows and columns. A Relational Database Management System (RDBMS) is a type of DBMS that consists of multiple tables in a database, which is related to each other through common
1A.10
columns. Various examples of RDBMS are Oracle, Microsoft SQL Server, and MySQL.
Consider a scenario, where you have to develop an application for an Airlines Company to maintain a record of daily transactions. You install SQL Server, design the Airlines database, and ask Airlines personnel to use it. Will the database alone be of any use to the Airline personnel? The answer is No! The task of updating the data in SQL Server by using SQL statements alone will be a tedious process. An application will need to be developed that is user friendly and provides a client, the options to retrieve, add, and modify data at the touch of a key. Thus, you need to develop an application that communicates with a database to perform the following tasks: Store and update the data in the database. Retrieve the data stored in the database and present it to users in a proper format. 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 Architecture
Java applications cannot directly communicate with a database to submit data and retrieve the results of queries. This is because a database can interpret only SQL statements and not Java language statements. For this reason, you need a
1A.11
mechanism to translate Java statements into SQL statements. The JDBC architecture provides the mechanism for this kind of translation. The JDBC architecture can be classified into two layers: JDBC application layer: Signifies a Java application that uses the JDBC API to interact with the JDBC drivers. A JDBC driver is software that a Java application uses to access a database. The JDBC driver manager of JDBC API connects the Java application to the driver. JDBC driver layer: Acts as an interface between a Java application and a database. This layer contains a driver, such as a SQL Server driver or an Oracle driver, which enables connectivity to a database. A driver sends the request of a Java application to the database. After processing the request, the database sends the response back to the driver. The driver translates and sends the response to the JDBC API. The JDBC API forwards it to the Java application. The following figure shows the JDBC architecture:
JDBC Architecture
INSTRUCTOR NOTES
Additional Input
JDBC versus ODBC: The differences between JDBC API and ODBC API are as follows:
1A.12
Programming languages such as VC.NET and VB.NET use ODBC API for database connectivity. However, Java uses JDBC API for database connectivity. JDBC is preferred to be used for Java programs than ODBC due to the following reasons: ODBC API is written using C. Java does not support some of the C language features such as pointers and destructors. JDBC is written using Java and is built on top of ODBC. Hence, Java programs use JDBC to interact with databases. If ODBC is used, ODBC driver manager and other drivers have to be installed manually and configured on each machine. Since, the JDBC driver is written in Java, it becomes automatically installable, portable, and secures to be used on any platform.
JDBC Drivers
When you develop JDBC applications, you need to use JDBC drivers to convert queries into a form that a particular database can interpret. The JDBC driver also retrieves the result of SQL statements and converts the result into equivalent JDBC API class objects that the Java application uses. As the JDBC driver only takes care of interactions with the database, any change made to the database does not affect the application. JDBC supports four types of drivers, they are: JDBC-ODBC Bridge driver Native-API Partly-Java driver JDBC-Net Pure-Java driver Native Protocol Pure-Java driver
1A.13
1A.14
1A.15
1A.16
INSTRUCTOR NOTES
Additional Input
Database Models: Various database models to store data are: Two-tier database model Three-tier database model The two-tier database model has only two working layers, client and server, where the client directly communicates with the server. A connection is established between the client and server to enable point-to-point communication. This connection in the two-tier database model remains active for the complete session of an application, even when the client and server are not exchanging information. In a two-tier database model, the client layer provides the interface and logic to interact with the database. For example, MS Access supports two-tier database model. You can create the front-end for an application that uses MS Access as back-end using any programming language, such as Java. The following figure shows a two-tier database model:
1A.17
In a three-tier database model, a client communicates with the server through a middleware. The three-tier database model has the following three working layers: Client: Consists of the user system interface that is the front end for the application. Middleware: Consists of the business logic for the application. Server: Consists of Database Management System (DBMS). The client in the three-tier database model passes all the data to the middleware, which performs the business logic validation. The middleware then transfers the data to the database server. The advantages of a three-tier database model are: Provides an abstraction layer. The three-tier database model enables you to create the user-interface that is independent of the database used. Provides a method to separate the responsibilities of the database developer and database user. The database-user interacts only with the client layer and has nothing to do with the middleware and server layer. On the other hand, the database-developer is concerned only with the server layer. Reduces the bandwidth consumption.
1A.18
1A.19
Introducing JDBC
NIIT
Lesson 1A / Slide 9 of 36
1A.20
Introducing JDBC
The steps to create JDBC application are: Load a driver Connect to a database Create and execute JDBC statements Handle SQL exceptions
NIIT
Lesson 1A / Slide 10 of 36
1A.21
Introducing JDBC
Loading a Driver
Programmatically: Using the forName() method Using the registerDriver()method Manually: By setting system property
NIIT
Lesson 1A / Slide 11 of 36
1A.22
Introducing JDBC
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");
NIIT
Lesson 1A / Slide 12 of 36
1A.23
Introducing JDBC
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);
NIIT
Lesson 1A / Slide 13 of 36
1A.24
Introducing JDBC
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
NIIT
Lesson 1A / Slide 14 of 36
1A.25
Introducing JDBC
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>)
NIIT
Lesson 1A / Slide 15 of 36
1A.26
Introducing JDBC
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)
NIIT
Lesson 1A / Slide 16 of 36
1A.27
Introducing JDBC
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
NIIT
Lesson 1A / Slide 17 of 36
1A.28
Introducing JDBC
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);
NIIT
Lesson 1A / Slide 18 of 36
1A.29
Introducing JDBC
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);
NIIT
Lesson 1A / Slide 19 of 36
1A.30
Introducing JDBC
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'"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str);
NIIT
Lesson 1A / Slide 20 of 36
1A.31
Introducing JDBC
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);
NIIT
Lesson 1A / Slide 21 of 36
1A.32
Introducing JDBC
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"; Statement stmt=con.createStatement(); stmt.execute(str);
JDBC and JavaBeans Lesson 1A / Slide 22 of 36
NIIT
1A.33
Introducing JDBC
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.
NIIT
Lesson 1A / Slide 23 of 36
INSTRUCTOR NOTES
Tell the students that java.sql package contains the classes and interfaces to develop JDBC applications. In this section, briefly discuss the classes and interfaces in the java.sql package as described in the chapter. After discussing the java.sql package, describe the steps involved in creating a JDBC application. You also need to explain how to create JDBC applications with the help of code snippets provided in this section.
You need to use database drivers and the JDBC API while developing a Java application to retrieve or store data in a database. The JDBC API classes and interfaces are available in the java.sql and the javax.sql packages. The classes
1A.34
and interfaces perform a number of tasks, such as establish and close a connection with a database, send a request to a database, retrieve data from a database, and update data in a database. 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. To query a database and display the result using Java applications, you need to: Load a driver Connect to a database Create and execute JDBC statements Handle SQL exceptions
INSTRUCTOR NOTES
Additional Input
Introduction to JDBC API: JDBC 3.0 Application Programming Interface (API) categorizes the API in two packages, java.sql and javax.sql. The java.sql package is the JDBC core API that is used to access and store client data sources. The javax.sql package is an extension to java.sql package. The javax.sql package is also referred as JDBC Optional Package API and enables you to communicate with the server side data sources. The java.sql package contains JDBC APIs that use the Java programming language to access and store data in the data sources. The drivers that are used to access the data stored in the data sources can be installed dynamically using the JDBC APIs that are defined in the java.sql package. In addition, the java.sql package enables you to read, write, and update the data stored in the data sources. The javax.sql package contains JDBC APIs that use the Java programming language to access and store server-side data sources. The javax.sql package
1A.35
provides a DataSource interface that enables you to connect with the data sources on the server. The various features of javax.sql package are connection pooling, distributed transactions, and rowsets.
Loading a Driver
The first step to develop a JDBC application is to load and register the required driver using the driver manager. You can load and register a driver: Programmatically: Using the forName() method Using the registerDriver()method Manually: By setting system property
Class.forName("<driver_name>");
You can load the JDBC-ODBC Bridge driver using the following method call: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
1A.36
Connecting to a Database
You create an object of the Connection interface to establish a connection of the Java application with a database. You can create multiple Connection objects in a Java application to access and retrieve data from multiple databases. The DriverManager class provides the getConnection() method to create a Connection object. The getConnection()method is an overloaded method that has the following three forms: Connection getConnection (String <url>): Accepts the JDBC URL of the database, which you need to access, as a parameter. You can use the following code snippet to connect to a database using the getConnection() method with a single parameter: String url = "jdbc:odbc:MyDataSource"; Connection con = DriverManager.getConnection(url); The syntax for a JDBC URL that is passed as a parameter to the getConnection() method is:
<protocol>:<subprotocol>:<subname>
A JDBC URL has the following three components: Protocol name: Indicates the name of the protocol that is used to access a database. In JDBC, the name of the access protocol is always jdbc. Sub-protocol name: Indicates the mechanism to retrieve data from a database. For example, if you use the JDBC-ODBC Bridge driver to access a database, then the name of the sub-protocol is odbc. Subname: Indicates the Data Source Name (DSN) that contains database information, such as the name of a database, location of the database server, user name, and password to access a database server. Connection getConnection (String <url>, String <username>, String <password>): Accepts the JDBC url of a database. It also accepts the user name and password of the authorized database user. You can use the following
1A.37
code snippet to specify the user name and password information to connect to a database: String url = "jdbc:odbc:MyDataSource"; Connection con = DriverManager.getConnection (url,"NewUser","NewPassword"); Connection getConnection (String <url>,Properties <properties>): Accepts the JDBC URL of a database and an object of java.util.Properties as parameters. You can specify information, such as user name and password in the Properties object by using the setProperty() method. You can use the following code snippet to specify properties to connect to a database: String url = "jdbc:odbc:MyDataSource"; Properties p = new Properties(); p.setProperty("user","NewUser"); p.setProperty("password","NewPassword"); Connection con = DriverManager.getConnection(url,p); In the preceding code snippet, p is the reference to an object of the Properties class. The username and password properties are set using the setProperty() method. After you create a connection, you need to write JDBC statements that are to be executed.
INSTRUCTOR NOTES
Additional Input
Database Objects: Each database consists of multiple objects that provide a logical framework to store data. Various database objects are: Table: Stores information about an entity in a tabular format. An entity is defined as a place, person, concept, or object about which you need to collect information. Various examples of entities are, employee, city, student, or product. Each entity consists of a number of attributes that describe the entity. For example, if employee is an entity then the attributes, such as name, address, designation, and salary can be used to describe it. In a table, each column represents an attribute of an entity. View: Obtains data from database tables and does not store any data of its own. If you make any change in the view, the change is reflected in the table or tables on which the view is based. For example, there is the employee table in a database that contains name, address, salary, department, and designation information of the employees. You can create a view based on the employee table that stores only name and address information of the employees.
1A.38
Stored Procedure and Function: Refer to the named blocks of Structured Query language (SQL) and procedural statements that perform specific actions. You can reuse the stored procedures and functions multiple times without rewriting or recompiling them. You need to call the stored procedures and functions explicitly to process them. Unlike stored procedures, functions always return a value. Index: Enhances database performance by speeding up the process to retrieve the information from a database. Trigger: Refers to the named block of the SQL and procedural statements that run automatically when certain operations are performed on the database object on which a trigger is defined.
1A.39
INSTRUCTOR NOTES
Additional Input
The Java applications that use SQL to retrieve information from the database need to use the corresponding Java data types to store the various SQL data types. The corresponding Java data types are used to store the SQL data types that are returned as the result of SQL queries. The following table lists the SQL data types and the corresponding wrapper classes in Java:
VARCHAR
String
LONGVARCHAR
String
NUMERIC
java.math.BigDecimal
DECIMAL
java.math.BigDecimal
1A.40
TINYINT
Integer
SMALLINT
Integer
INTEGER
Integer
BIGINT
Long
REAL
Float
FLOAT
Double
DOUBLEPRECISION
Double
BINARY
byte[]
VARBINARY
byte[]
LONGVARBINARY
byte[]
DATE
java.sql.Data
TIME
java.sql.Time
TIMESTAMP
java.sql.Timestamp
1A.41
You can use the DML statements, INSERT, UPDATE, and DELETE, in Java applications to modify the data stored in the database tables. You can also use the Data Definition Language(DDL) statements, CREATE, ALTER, and DROP, in Java applications to define or change the structure of database objects. 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
Querying a Table
You can retrieve data from a table using the SELECT statement. The SELECT statement is executed using the executeQuery() method and returns the output in the form of a ResultSet object. You can use the following code snippet to retrieve data from the authors table: String str = "SELECT * FROM authors"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(str); In the preceding code snippet, str contains the SELECT statement that retrieves data from the authors table. The result is stored in the ResultSet object, rs. When you need to retrieve selected rows from a table, the condition to retrieve the rows is specified in the WHERE clause of the SELECT statement. You can use the following code snippet to retrieve selected rows from the authors table: String str = "SELECT * FROM authors WHERE city=Oakland"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(str); In the preceding code snippet, executeQuery() method retrieves the details from authors tables for a particular city.
1A.42
Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); In the preceding code snippet, str contains the INSERT statement that you need to send to a database. The object of the Statement interface, stmt, executes the INSERT statement using the executeUpdate() method and returns the number of rows inserted in the table to the count variable.
Creating a Table
You use the CREATE TABLE statement to create and define the structure of a table in a database. You can use the following code snippet in a Java application to create a table: 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);
1A.43
In the preceding code snippet, the str String contains the CREATE TABLE statement to create the MyProduct table. The execute() method is used to process the CREATE TABLE statement.
1A.44
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. You can use the following code snippet to catch SQLException: try { String str = "DELETE FROM authors WHERE au_id='998-72-3568'"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); } catch(SQLException sqlExceptionObject) { System.out.println("Display Error Code"); System.out.println("SQL Exception"+ sqlExceptionObject.getErrorCode()); } In the preceding code snippet, if the DELETE statement at runtime throws an SQLException then it is handled using the try catch block. The sqlExceptionObject is an object of the SQLException class and is used to invoke the getErrorCode() method.
1A.45
Introducing JDBC
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.
NIIT
Lesson 1A / Slide 24 of 36
1A.46
Introducing JDBC
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. Specifies that the cursor of the ResultSet object is scrollable and it does not reflect changes in the data made by other users. Specifies that the cursor of the ResultSet object moves in forward direction only from the first row to the last row.
TYPE_SCROLL_INSENSITIVE
TYPE_FORWARD_ONLY
NIIT
Lesson 1A / Slide 25 of 36
1A.47
Introducing JDBC
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. Specifies the concurrency mode that allows you to update the ResultSet object.
CONCUR_UPDATABLE
NIIT
Lesson 1A / Slide 26 of 36
1A.48
Introducing JDBC
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. Specifies that a ResultSet object should be closed after data is committed to the database.
CLOSE_CURSORS_AT_COMMIT
NIIT
Lesson 1A / Slide 27 of 36
1A.49
Introducing JDBC
NIIT
Lesson 1A / Slide 28 of 36
1A.50
Introducing JDBC
The following tables lists the methods of ResultSet interface: Method boolean first() boolean isFirst() boolean beforeFirst() boolean isBeforeFirst() boolean last() boolean isLast()
NIIT
Description Shifts the control of a result set cursor to the first row of the result set. Determines whether the result set cursor points to the first row of the result set. Shifts the control of a result set cursor before the first row of the result set. Determines whether the result set cursor points before the first row of the result set. Shifts the control of a result set cursor to the last row of the result set. Determines whether the result set cursor points to the last row of the result set.
JDBC and JavaBeans Lesson 1A / Slide 29 of 36
1A.51
Introducing JDBC
The methods of ResultSet interface (Contd.) Method boolean afterLast() boolean isAfterLast() boolean previous() boolean absolute(int i) boolean relative(int i)
NIIT
Description Shifts the control of a result set cursor after the last row of the result set. Determines whether the result set cursor points after the last row of the result set. Shifts the control of a result set cursor to the previous row of the result set. Shifts the control of a result set cursor to the row number that you specify as a parameter. 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 Lesson 1A / Slide 30 of 36
1A.52
Introducing JDBC
Description Updates a row of the current ResultSet object and the underlying database table. Inserts a row in the current ResultSet object and the underlying database table. Deletes a row from the current ResultSet object and the underlying database table. Updates the specified column with the given string value. Updates the specified column with the given int value.
JDBC and JavaBeans Lesson 1A / Slide 31 of 36
INSTRUCTOR NOTES
You can ask the students to discuss the purpose of storing data in a ResultSet object. Tell the students that there are various types of result sets to store the data retrieved from a database. You need to explain the procedure to create different types of result sets as discussed in the chapter.
When you execute a query to retrieve data from a table using a Java application, the output of the query is stored in a ResultSet object in a tabular format. A ResultSet object maintains a cursor that enables you to move through the rows stored in a ResultSet object. By default, the ResultSet object maintains a cursor that moves in the forward direction only. As a result, it moves from the first row to the last row in the ResultSet. You cannot update the default ResultSet object. The cursor in the ResultSet object initially points before the first row.
1A.53
ResultSet Fields
TYPE_SCROLL_SENTITIVE
Description
Specifies that the cursor of the ResultSet object is scrollable and it reflects the changes in the data made by other users. Specifies that the cursor of the ResultSet object is scrollable and it does not reflect changes in the data made by other users. Specifies that the cursor of the ResultSet object moves in forward direction only from the first row to the last row.
TYPE_SCROLL_INSENSITIVE
TYPE_FORWARD_ONLY
The following table lists various fields of the ResultSet interface that you can use to specify different concurrency modes of result sets:
ResultSet Fields
CONCUR_READ_ONLY
Description
Specifies the concurrency mode that does not allow you to update the ResultSet object.
1A.54
ResultSet Fields
CONCUR_UPDATABLE
Description
Specifies the concurrency mode that allows you to update the ResultSet object.
The following table lists various fields of the ResultSet interface that you can use to specify different cursor states of result sets:
ResultSet Fields
HOLD_CURSORS_OVER_COMMIT
Description
Specifies that a ResultSet object should not be closed after data is committed to the database. Specifies that a ResultSet object should be closed after data is committed to the database.
CLOSE_CURSORS_AT_COMMIT
The createStatement() method is an overloaded method that has three prototypes. The following are three overloaded forms of the createStatement() method: Statement createStatement(): Does not accept any parameter. This method creates a default ResultSet object that only allows forward scrolling. Statement createStatement(int, int): Accepts two parameters. The first parameter indicates the ResultSet type that determines whether or not, a result set cursor can move backward. The second parameter indicates the concurrency mode for the result set that determines whether the data in result set can be updated. This method creates a ResultSet object with the given type and concurrency. Statement createStatement(int, int, int): Accepts three parameters. In addition to the ResultSet types and the concurrency mode, this method accepts a third parameter. This parameter indicates whether or not, the result set is closed after committing data to the database. This method creates a ResultSet object with the given type, concurrency, and state.
1A.55
Method
boolean first() boolean isFirst() boolean beforeFirst() boolean isBeforeFirst() boolean last() boolean isLast() boolean afterLast() boolean isAfterLast() boolean previous() boolean absolute(int i) boolean relative(int i)
Description
Shifts the control of a result set cursor to the first row of the result set. Determines whether the result set cursor points to the first row of the result set. Shifts the control of a result set cursor before the first row of the result set. Determines whether the result set cursor points before the first row of the result set. Shifts the control of a result set cursor to the last row of the result set. Determines whether the result set cursor points to the last row of the result set. Shifts the control of a result set cursor after the last row of the result set. Determines whether the result set cursor points after the last row of the result set. Shifts the control of a result set cursor to the previous row of the result set. Shifts the control of a result set cursor to the row number that you specify as a parameter. Shifts the control of a result set cursor, forward or backward, relative to the row number that you specify as a parameter. This method accepts either a positive or a negative value as a parameter.
You can create a scrollable result set that scrolls backward or forward through the rows in the result set. You can use the following code snippet to create a read only scrollable result set: Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs=stmt.executeQuery ("SELECT * FROM authors"); You can determine the location of the result set cursor using the methods in the ResultSet interface. You can use the following code snippet to determine if the result set cursor is before the first row in the result set:
1A.56
if(rs.isBeforeFirst()==true) System.out.println("Result set cursor is before the first row in the result set"); In the preceding code, rs is the ResultSet object that calls the isBeforeFirst() method. You can move to a particular row, such as first or last, in the result set using the methods in the ResultSet interface. You can use the following code snippet to move the result set cursor to the first row in the result set: if(rs.first()==true) System.out.println(rs.getString(1) + ", " + rs.getString(2)+ ", " + rs.getString(3)); In the preceding code snippet, rs is the ResultSet object that calls the first() method. Similarly, you can move the result set cursor to the last row in the result set using the last() method. If you want to move to any particular row of a result set, you can use the absolute() method. For example, if the result set cursor is at the first row and you want to scroll to the fourth row, you should enter 4 as a parameter when you call the absolute() method, as shown in the following code snippet: System.out.println("Using absolute() method"); rs.absolute(4); int rowcount = rs.getRow(); System.out.println("rowNum should be 4 " + rowcount); You can pass a negative value to the absolute() method to set the cursor to a row with regard to the last row of the result set. For example, to set the cursor to the row above the last row, specify rs.absolute(-2). 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
void updateRow()
Description
Updates a row of the current ResultSet object and the underlying database table. Inserts a row in the current ResultSet object and the underlying database table. Deletes a row from the current ResultSet object and the underlying database table.
void insertRow()
void deleteRow()
1A.57
Method
void updateString() void updateInt()
Description
Updates the specified column with the given string value. Updates the specified column with the given int value.
You can use the following code snippet to modify the author information using the updatable result set: Statement stmt = con.createStatement(); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT au_id, city, state FROM authors WHERE au_id='893-72-1158' "); rs.next(); rs.updateString("state", "NY"); rs.updateString("city", "Columbia"); rs.updateRow(); In the preceding code snippet, the row is retrieved from the authors table where author id is 893-72-1158. In the retrieved row, the value in the state column is changed to NY and the value in the city column is changed to Columbia.
INSTRUCTOR NOTES
Additional Input
Creating updatable result set: The type 4 JDBC driver can be used to create updatable ResultSet. It can be downloaded from, http://www.microsoft.com/downloads. You can use the following code to create an updatable ResultSet using the type 4 JDBC driver: import java.sql.*; import javax.sql.*; import javax.sql.DataSource; import javax.naming.*; public class UpdatableResultset { public static void main(String args[]) { try { //Initialize and load the JDBC-ODBC bridge driver
1A.58
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerD river"); //Establish a connection with a data source Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver: //dc06:1433","administrator",""); //Create a Statement object Statement stmt = con.createStatement(); //Create an Updatable resultset stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //Retrieve author information ResultSet rs = stmt.executeQuery("Select au_id,city, state from pubs.dbo.authors where au_id='893-72-1158' "); rs.next(); //Update data rs.updateString("state", "OR"); rs.updateString("city", "Corvallis"); rs.updateRow(); //Close a data source connection con.close(); con = DriverManager.getConnection("jdbc:microsoft:sqlserver: //dc06:1433","administrator",""); stmt = con.createStatement(); rs = stmt.executeQuery("Select au_id,city, state from pubs.dbo.authors where au_id='893-72-1158' "); while(rs.next()) System.out.println(rs.getString(1) + ", " + rs.getString(2) + ", " + rs.getString(3)); con.close(); } catch(Exception e) { System.out.println("Error " + e); } }
In the preceding code, the author information is modified using the Updatable resultset. The value in the state column is changed to OR and value in the city column is changed to Corvallis.
1A.59
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.
NIIT
Lesson 1A / Slide 32 of 36
1A.60
Introducing JDBC
Solution
JDBC-ODBC Bridge driver is to be used for creating the application. To solve the above problem, perform the following tasks: 1. Create a Data Source Name (DSN). 2. Code the application. 3. Compile and execute the application.
NIIT
Lesson 1A / Slide 33 of 36
INSTRUCTOR NOTES
Start this section by explaining the purpose of creating DSN. Explain the steps to create DSN as discussed in the section. After creating DSN, you can explain the application to be demonstrated. Compile and run the Authorsinfo.java code file to execute the application.
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.
1A.61
Solution
JDBC-ODBC Bridge driver is to be used for creating the application. To solve the above problem, perform the following tasks: 1. Create a Data Source Name (DSN). 2. Code the application. 3. Compile and execute the application.
1. Create a DSN
To create a DSN, you need to perform following steps: a. Selecting the required driver for a DSN b. Specifying the connection details for a DSN c. Testing the created DSN
1A.62
4. To select a driver for creating a DSN, from the list of drivers, click the Add button. 5. To connect to SQL Server 2000, select the SQL Server option from the Name list box in the Create New Data Source dialog box, as shown in the following figure:
6. To complete the task of selecting the driver for the creating a DSN, click the Finish button.
1A.63
2. To select the required SQL Server select the name of the SQL server from the Server drop-down list box and click the Next button. 3. To indicate how the SQL Server should authenticate a login ID, select the With SQL Server authentication using a login ID and password entered by the user option. The Login ID and Password text boxes become active as shown in the following figure:
4. To indicate the user name and password to connect to the database, type the user name in the Login ID text box and the password in the Password text box and click the Next button.
1A.64
5. To enable the database drop-down list, select the Change the default database to option, as shown in the following figure:
6. To select the required database select the name of the database from the drop-down list box and click the Next button. 7. To select the language for the system messages, select the Change the language of SQL Server system messages to option, as shown in the following figure:
8. To indicate the language for the system messages, select English from the drop down list and click the Finish button. The ODBC Microsoft SQL Server
1A.65
Setup dialog box appears with all the details about the created DSN, as shown in the following figure:
1A.66
2. To return to the ODBC Microsoft SQL Server Setup dialog box, click the OK button. 3. To save the configuration settings for the new data source, click the OK button. 4. To verify that the DSN is created, check the name of the created DSN in the User Data Source list box of the ODBC Data Source Administrator dialog box and click the OK button. The following figure shows the ODBC Data Source Administrator dialog box:
1A.67
1A.68
/*Create a Statement object to process the SELECT statement*/ Statement stmt=con.createStatement(); /*Execute the SELECT SQL statement*/ ResultSet rs=stmt.executeQuery(str); System.out.println("Author ID\tFirst Name\tLast Name\tCity"); /*Display the result*/ while (rs.next()) { String id=rs.getString("au_id"); String lname=rs.getString("au_lname"); String fname=rs.getString("au_fname"); String city=rs.getString("city"); System.out.print(id+"\t"); /*Use tab to format the output. If the number of characters in a data value are less than or equal to 7, the two tabs are used to specify the position to display the next column in the ResultSet*/ if (fname.length() <=7) System.out.print(fname+"\t\t"); else System.out.print(fname+"\t"); if (lname.length() <=7) System.out.print(lname+"\t\t"); else System.out.print(lname+"\t"); System.out.println(city); } con.close(); } catch(Exception ex) { System.out.println("Error occurred"); System.out.println("Error:"+ex); } } }
1A.69
The following figure shows the output of the code that displays the information from the authors table:
1A.70
SUMMARY
Introducing JDBC
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.
NIIT
Lesson 1A / Slide 34 of 36
1A.71
Introducing JDBC
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
NIIT
Lesson 1A / Slide 35 of 36
1A.72
Introducing JDBC
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
NIIT
Lesson 1A / Slide 35 of 36
1A.73
Introducing JDBC
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.
NIIT
Lesson 1A / Slide 36 of 36
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 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.
1A.74
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 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.
1A.75
1A.76