You are on page 1of 76

LESSON: 1A

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

JDBC and JavaBeans

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

JDBC and JavaBeans

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

JDBC and JavaBeans

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

JDBC and JavaBeans

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

JDBC and JavaBeans

Lesson 1A / Slide 2 of 36

JDBC and JavaBeans

1A.4

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 3 of 36

1A.5

JDBC and JavaBeans

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 4 of 36

JDBC and JavaBeans

1A.6

Introducing JDBC

Database Connectivity (Contd.)

JDBC-ODBC Bridge driver

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 5 of 36

1A.7

JDBC and JavaBeans

Introducing JDBC

Database Connectivity (Contd.)

Native-API Partly-Java driver

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 6 of 36

JDBC and JavaBeans

1A.8

Introducing JDBC

Database Connectivity (Contd.)

JDBC-Net Pure-Java driver

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 7 of 36

1A.9

JDBC and JavaBeans

Introducing JDBC

Database Connectivity (Contd.)

Native-Protocol Pure-Java driver

NIIT

JDBC and JavaBeans

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

JDBC and JavaBeans

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:

Database Connectivity Using 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

JDBC and JavaBeans

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:

JDBC and JavaBeans

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

The JDBC-ODBC Bridge Driver


The JDBC-ODBC Bridge driver is called the Type 1 driver. The JDBC-ODBC Bridge driver converts JDBC calls to Open Database Connectivity (ODBC) calls. ODBC is an open standard API to communicate with databases. The JDBC-ODBC bridge driver enables a Java application to use any database that supports ODBC driver. A Java application cannot interact directly with the ODBC driver. For this reason, the application uses the JDBC-ODBC Bridge driver that works as an interface between the application and the ODBC driver. To use the JDBC-ODBC Bridge driver you need to have the ODBC driver installed on the client computer. The JDBC-ODBC Bridge driver is usually used in stand-alone applications. The following figure shows the working of the JDBC-ODBC Bridge driver:

1A.13

JDBC and JavaBeans

JDBC-ODBC Bridge Driver

The Native-API Partly-Java Driver


The Native-API Partly-Java driver is called the Type 2 driver. It uses the local native libraries provided by the database vendors to access databases. The JDBC driver maps the JDBC calls to the native method calls, which are passed to the local native Call Level Interface (CLI). This interface consists of functions written in C to access databases. To use the Type 2 driver, CLI needs to be loaded on the client computer. As opposed to the JDBC-ODBC Bridge driver, the Native-API Partly-Java driver does not have an ODBC intermediate layer. As a result, this driver has a better performance than the JDBC-ODBC Bridge driver. This driver is usually used for network-based applications. The following figure shows the working of the Native-API Partly-Java driver:

JDBC and JavaBeans

1A.14

Native-API Partly-Java Driver

The JDBC-Net Pure-Java Driver


The JDBC-Net Pure-Java driver is called the Type 3 driver. You can use the JDBC-Net Pure-Java driver over the Web while connecting applets with databases. The JDBC-Net Pure-Java driver consists of client and server portions. The client portion contains pure Java functions and the server portion contains Java and native methods. The Java application sends JDBC calls to the JDBC-Net Pure-Java driver client portion, which in turn, translates JDBC calls into database calls. The database calls are sent to the server portion of the JDBC-Net Pure-Java driver that forwards the request to the database. When you use the JDBC-Net Pure-Java driver, CLI native libraries are loaded on the server. The following figure shows the working of the JDBC-Net PureJava driver:

1A.15

JDBC and JavaBeans

JDBC-Net Pure-Java Driver

The Native-Protocol Pure-Java Driver


The Native-Protocol Pure-Java driver is called the Type 4 driver. It is a Java driver that interacts with the database directly using a vendor-specific network protocol. As opposed to the other JDBC drivers, you do not require to install any vendor-specific libraries to use the Type 4 driver. DataDirect Technologies provide Type 4 driver for various databases such as MS SQL Server, AS/400, and DB2. This driver is usually used for enterprise applications. The following figure shows the working of the Native Protocol Pure-Java driver:

JDBC and JavaBeans

1A.16

Native-Protocol Pure-Java Driver

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

JDBC and JavaBeans

Two-tier Database Model

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.

JDBC and JavaBeans

1A.18

The following figure shows a three-tier database model:

Three-Tier Database Model

1A.19

JDBC and JavaBeans

USING JDBC API

Introducing JDBC

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.

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 9 of 36

JDBC and JavaBeans

1A.20

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 10 of 36

1A.21

JDBC and JavaBeans

Introducing JDBC

Using JDBC API (Contd.)

Loading a Driver

Programmatically: Using the forName() method Using the registerDriver()method Manually: By setting system property

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 11 of 36

JDBC and JavaBeans

1A.22

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 12 of 36

1A.23

JDBC and JavaBeans

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 13 of 36

JDBC and JavaBeans

1A.24

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 14 of 36

1A.25

JDBC and JavaBeans

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 15 of 36

JDBC and JavaBeans

1A.26

Introducing JDBC

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)

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 16 of 36

1A.27

JDBC and JavaBeans

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 17 of 36

JDBC and JavaBeans

1A.28

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 18 of 36

1A.29

JDBC and JavaBeans

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 19 of 36

JDBC and JavaBeans

1A.30

Introducing JDBC

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'"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str);

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 20 of 36

1A.31

JDBC and JavaBeans

Introducing JDBC

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

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 21 of 36

JDBC and JavaBeans

1A.32

Introducing JDBC

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"; Statement stmt=con.createStatement(); stmt.execute(str);
JDBC and JavaBeans Lesson 1A / Slide 22 of 36

NIIT

1A.33

JDBC and JavaBeans

Introducing JDBC

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.

NIIT

JDBC and JavaBeans

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

JDBC and JavaBeans

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

JDBC and JavaBeans

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

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 syntax to load a JDBC driver to access a database is:

Class.forName("<driver_name>");
You can load the JDBC-ODBC Bridge driver using the following method call: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Using the registerDriver() Method


You can create an instance of the Driver class to load a JDBC driver. The syntax to declare an instance of the Driver class is:

Driver d=new <driver name>;


You can use the following statement to create an instance of the Driver class: Driver d = new sun.jdbc.odbc.JdbcOdbcDriver(); Once you have created the Driver object, call the registerDriver() method to register it with the DriverManager. You can register the JDBC-ODBC Bridge driver using the following method call to registerDriver() method: DriverManager.registerDriver(d);

JDBC and JavaBeans

1A.36

Setting System Property


Driver can also be loaded by setting system property for JDBC drivers. You add the driver name to the jdbc.drivers system property to load a JDBC driver. You 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 In the preceding command, jdbc.drivers is the property name and sun.jdbc.odbc.JdbcOdbcDriver is the value that you need to set for the property. After you load a driver, you need to establish the connection with a database.

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

JDBC and JavaBeans

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.

JDBC and JavaBeans

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.

Creating and Executing JDBC Statements


You need to create a Statement object to send requests to and retrieve results from a database. The Connection object provides the createStatement() method to create a Statement object. You can use the following code snippet to create a Statement object: Connection con = DriverManager.getConnection ("jdbc:odbc:MyDataSource","NewUser","NewPassword"); Statement stmt = con.createStatement(); You can use static SQL statements to send requests to a database. The SQL statements that do not contain runtime parameters are called static SQL statements. You can send SQL statements to a database using the Statement object. The Statement interface contains the following methods to send static SQL statements to a database: ResultSet executeQuery(String str): Executes an SQL statement and returns a single object of the type, ResultSet. This object provides you with the methods to access the data from a result set. The executeQuery() method should be used when you need to retrieve data from a database table using the SELECT statement. The syntax to use the executeQuery() method is:

Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(<SQL statement>);


In the preceding syntax, stmt is a reference to the object of the Statement interface. The executeQuery() method executes an SQL statement and the result retrieved from a database is stored in rs, the ResultSet object. int executeUpdate(String str): Executes the SQL statements and returns the number of data rows that are affected after processing the SQL statement. When you need to modify data in a database table using the Data Manipulation Language(DML) statements, INSERT, DELETE, and UPDATE, you can use the executeUpdate() method. The syntax to use the executeUpdate() method is:

1A.39

JDBC and JavaBeans

Statement stmt = con.createStatement(); int count = stmt.executeUpdate(<SQL statement>);


In the preceding syntax, the executeUpdate() method executes an SQL statement and number of rows affected in a database is stored in count, the int type variable. boolean execute(String str): Executes an SQL statement and returns a boolean value. You can use this method when the type of SQL statement passed as parameter is not known or when the statement being executed returns a result set or an update count. The execute() method returns true if the result of the SQL statement is an object of ResultSet and false if it is an update count. The syntax to use the execute() methods is:

Statement stmt = con.createStatement(); stmt.execute(<SQL statement>);

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:

SQL Data Types


CHARACTER

Java Wrapper Class


String

VARCHAR

String

LONGVARCHAR

String

NUMERIC

java.math.BigDecimal

DECIMAL

java.math.BigDecimal

JDBC and JavaBeans

1A.40

SQL Data Types


BIT

Java Wrapper Class


Boolean

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

JDBC and JavaBeans

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.

Inserting Rows in a Table


You can add rows in an existing table using the INSERT statement. The executeUpdate() method enables you to add rows in a table. You can use the following code snippet to insert a row in the authors table: 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')";

JDBC and JavaBeans

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.

Updating Rows in a Table


You can modify the existing information in a table using the UPDATE statement. You can use the following code snippet to modify a row in the authors table: String str = "UPDATE authors SET address='10932 Second Av.' WHERE au_id='998-72-3568'"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); In the preceding code snippet, str contains the UPDATE statement that you need to send to a database. The Statement object executes this statement using the executeUpdate() method and returns the number of rows modified in the table to the count variable.

Deleting Rows from a Table


You can delete existing information from a table using the DELETE statement. You can use the following code snippet to delete a row from the authors table: String str = "DELETE FROM authors WHERE au_id='998-72-3568'"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); In the preceding code snippet, str contains the DELETE statement that you need to send to a database. The Statement object executes this statement using the executeUpdate() method and returns the number of rows deleted from 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

JDBC and JavaBeans

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.

Altering and Dropping a Table


DDL provides the ALTER statement to modify the definition of database object. You use the ALTER TABLE statement to modify the structure of a table. For example, you use this statement to add a new column in a table, change the data type and width of an existing column, and add a constraint to a column. You can use the following code snippet to use the ALTER TABLE statement in a Java application to add a column the MyProduct table: String str="ALTER TABLE MyProduct " +"ADD quantity INTEGER"; Statement stmt=con.createStatement(); stmt.execute(str); DDL provides the DROP statement to drop an object from a database. You use the DROP TABLE statement to drop a table from a database. You can use the following code snippet to drop the MyProduct table using a Java application: String str="DROP TABLE MyProduct"; Statement stmt=con.createStatement(); stmt.execute(str); When you create JDBC applications you need to handle exceptions. The execute methods throw SQLException when any runtime error occurs while executing SQL statements.

Handling SQL Exceptions


The java.sql package provides the SQLException class, which is derived from the java.lang.Exception class. The SQLException is thrown by various methods in the JDBC API and enables you to determine the reason of the errors that occur while connecting a Java application to a database. You can catch the SQLException in a Java application using the try and catch exception handling block. The SQLException class provides the following error information: Error message: Is a string that describes error. Error code: Is an integer value that is associated with error. The error code is vendor-specific and depends upon database in use. SQL state: Is an X/OPEN error code that identifies the error. Various vendors provide different error messages to define same error. As a result, an error may give different error messages. The X/OPEN error code is a standard message associated with an error that can identify the error across multiple databases. The SQLException class contains various methods that provide error information. The methods in the SQLException class are:

JDBC and JavaBeans

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

JDBC and JavaBeans

ACCESSING RESULT SETS

Introducing JDBC

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.

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 24 of 36

JDBC and JavaBeans

1A.46

Introducing JDBC

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. 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

JDBC and JavaBeans

Lesson 1A / Slide 25 of 36

1A.47

JDBC and JavaBeans

Introducing JDBC

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. Specifies the concurrency mode that allows you to update the ResultSet object.

CONCUR_UPDATABLE

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 26 of 36

JDBC and JavaBeans

1A.48

Introducing JDBC

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. Specifies that a ResultSet object should be closed after data is committed to the database.

CLOSE_CURSORS_AT_COMMIT

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 27 of 36

1A.49

JDBC and JavaBeans

Introducing JDBC

Accessing Result Sets (Contd.)

The createStatement() method has the following three overloaded forms:

Statement createStatement() Statement createStatement(int, int) Statement createStatement(int, int, int)

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 28 of 36

JDBC and JavaBeans

1A.50

Introducing JDBC

Accessing Result Sets (Contd.)

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

JDBC and JavaBeans

Introducing JDBC

Accessing Result Sets (Contd.)

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

JDBC and JavaBeans

1A.52

Introducing JDBC

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 void updateRow() void insertRow() void deleteRow() void updateString() void updateInt()
NIIT

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

JDBC and JavaBeans

Types of Result Sets


You can create various types of ResultSet objects to store the output returned by a database after executing SQL statements. Various types of ResultSet objects are: Read only: Allows you to only read the rows in a ResultSet object. Forward only: Allows you to move the result set cursor from first row to last row in forward direction only. Scrollable: Allows you to move 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. You can specify the type of a ResultSet object using the createStatement() method of the Connection interface. The createStatement() accepts ResultSet fields as parameters to create different types of the ResultSet objects. The following table lists various fields of the ResultSet interface that you can use to create different types of result sets:

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.

JDBC and JavaBeans

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.

Methods of ResultSet Interface


The ResultSet interface contains various methods that enable you to move the cursor through the result set. The following table lists the methods of the ResultSet interface:

1A.55

JDBC and JavaBeans

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:

JDBC and JavaBeans

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

JDBC and JavaBeans

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

JDBC and JavaBeans

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

JDBC and JavaBeans

CREATING A JDBC APPLICATION TO QUERY A DATABASE


Introducing JDBC

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.

NIIT

JDBC and JavaBeans

Lesson 1A / Slide 32 of 36

JDBC and JavaBeans

1A.60

Introducing JDBC

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: 1. Create a Data Source Name (DSN). 2. Code the application. 3. Compile and execute the application.

NIIT

JDBC and JavaBeans

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

JDBC and JavaBeans

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

a. Selecting the required driver for a DSN


1. To select the required driver for the DSN, you need to first open the Control Panel window. Select the Start Settings Control Panel command to open the Control Panel window. 2. To access the options that enable you to configure the administrative settings, double-click the Administrative Tools icon. 3. To open the ODBC Data Source Administrator dialog box, double-click the Data sources (ODBC) icon. The following figure shows the ODBC Data Source Administrator dialog box:

ODBC Data Source Administrator Dialog Box

JDBC and JavaBeans

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:

Create New Data Source Dialog Box

6. To complete the task of selecting the driver for the creating a DSN, click the Finish button.

b. Specifying the Connection Details for a DSN


After you select the required driver for a DSN, you need to specify the connection details for a DSN. 1. To create a DSN, type the name of the data source in the Name text box of the Create a New Data Source to SQL Server dialog box, as shown in the following figure:

1A.63

JDBC and JavaBeans

Create a New Data Source to SQL Server Dialog Box

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:

Selecting an Authentication Option

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.

JDBC and JavaBeans

1A.64

5. To enable the database drop-down list, select the Change the default database to option, as shown in the following figure:

Selecting a Default Database

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:

Changing the SQL Server System Messages Language

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

JDBC and JavaBeans

Setup dialog box appears with all the details about the created DSN, as shown in the following figure:

ODBC Microsoft SQL Server Setup Dialog Box

c. Testing the created DSN


1. To test the created DSN for the connection with the database, click the Test Data Source button. The messages regarding the connectivity test appear in the SQL Server ODBC Data Source Test dialog box as shown in the following figure:

JDBC and JavaBeans

1A.66

SQL Server ODBC Data Source Test Dialog Box

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

JDBC and JavaBeans

Displaying the MyDataSource Data Source

2. Code the Application


You need to write the code to perform the following tasks in the application: 1. Load the JDBC-ODBC Bridge driver. 2. Connect to the MyDataSource DSN. 3. Create and execute JDBC statements. 4. Display the result. You can use the following code to create the application: import java.sql.*; public class AuthorsInfo { public static void main(String args[]) { try { String str="SELECT * FROM authors WHERE city LIKE 'O%'"; /*Initialize and load the JDBC-ODBC Bridge driver*/ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); /*Establish a connection with a data source*/ Connection con=DriverManager.getConnection("jdbc:odbc:MyDataSour ce","administrator", "");

JDBC and JavaBeans

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

The preceding code is saved as an AuthorsInfo.java file.

3. Compile and Execute the Application


The command to compile the AuthorsInfo application is:

javac AuthorsInfo.java The command to execute the AuthorsInfo application is:


java AuthorsInfo

1A.69

JDBC and JavaBeans

The following figure shows the output of the code that displays the information from the authors table:

Output of AuthorsInfo Application

JDBC and JavaBeans

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

JDBC and JavaBeans

Lesson 1A / Slide 34 of 36

1A.71

JDBC and JavaBeans

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

JDBC and JavaBeans

Lesson 1A / Slide 35 of 36

JDBC and JavaBeans

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

JDBC and JavaBeans

Lesson 1A / Slide 35 of 36

1A.73

JDBC and JavaBeans

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

JDBC and JavaBeans

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.

JDBC and JavaBeans

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

JDBC and JavaBeans

JDBC and JavaBeans

1A.76

You might also like