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

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

• 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 .) • JDBC Architecture: • Provides the mechanism to translate Java statements into SQL statements.Introducing JDBC Database Connectivity (Contd.

• 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.) • JDBC Drivers: • Convert SQL statements into a form that a particular database can interpret.6 .Introducing JDBC Database Connectivity (Contd.

Introducing JDBC Database Connectivity (Contd.7 JDBC and JavaBeans .) • JDBC-ODBC Bridge driver ©NIIT JDBC and JavaBeans Lesson 1A / Slide 5 of 36 1A.

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 .

and delete information. DBMS. store. Each database stores information in a table. You can also ask the students about the feasibility of using RDBMS for doing data entry or modifying the data. A Relational Database Management System (RDBMS) is a type of DBMS that consists of multiple tables in a database. Additional Input Database Concepts: Database is a collection of related information stored in an organized form on a computer such as computerized library system. You can further probe them as to how should one do data entry. and RDBMS. which is related to each other through common JDBC and JavaBeans 1A. which consists of rows and columns. which is software that enables you to access.) • 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.10 . modify. Databases are managed by Database Management System (DBMS).Introducing JDBC Database Connectivity (Contd.

you need a 1A. add.columns. Microsoft SQL Server. Retrieve the data stored in the database and present it to users in a proper format. you need to develop an application that communicates with a database to perform the following tasks: Store and update the data in the database. and MySQL. Consider a scenario. where you have to develop an application for an Airlines Company to maintain a record of daily transactions. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases. You install SQL Server. An application will need to be developed that is user friendly and provides a client. This is because a database can interpret only SQL statements and not Java language statements. and modify data at the touch of a key.11 JDBC and JavaBeans . Various examples of RDBMS are Oracle. and ask Airlines personnel to use it. 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. For this reason. Thus. 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. design the Airlines database. the options to retrieve.

The JDBC API forwards it to the Java application. This layer contains a driver. 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. After processing the request. the database sends the response back to the driver. The driver translates and sends the response to the JDBC API. which enables connectivity to a database. 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. The JDBC architecture provides the mechanism for this kind of translation. JDBC driver layer: Acts as an interface between a Java application and a database. The JDBC driver manager of JDBC API connects the Java application to the driver. A JDBC driver is software that a Java application uses to access a database.12 . such as a SQL Server driver or an Oracle driver.mechanism to translate Java statements into SQL statements. A driver sends the request of a Java application to the database.

portable. However.Programming languages such as VC. any change made to the database does not affect the application. JDBC is written using Java and is built on top of ODBC. The JDBC-ODBC Bridge driver converts JDBC calls to Open Database Connectivity (ODBC) calls. it becomes automatically installable. For this reason. To use the JDBC-ODBC Bridge driver you need to have the ODBC driver installed on the client computer. If ODBC is used. JDBC is preferred to be used for Java programs than ODBC due to the following reasons: ODBC API is written using C.NET and VB. A Java application cannot interact directly with the ODBC driver. the JDBC driver is written in Java. you need to use JDBC drivers to convert queries into a form that a particular database can interpret. ODBC is an open standard API to communicate with databases.NET use ODBC API for database connectivity. the application uses the JDBC-ODBC Bridge driver that works as an interface between the application and the ODBC driver. Java uses JDBC API for database connectivity. JDBC supports four types of drivers. Java does not support some of the C language features such as pointers and destructors. Since.13 JDBC and JavaBeans . Java programs use JDBC to interact with databases. Hence. ODBC driver manager and other drivers have to be installed manually and configured on each machine. The JDBC-ODBC Bridge driver is usually used in stand-alone applications. As the JDBC driver only takes care of interactions with the database. The following figure shows the working of the JDBC-ODBC Bridge driver: 1A. 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. 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. JDBC Drivers When you develop JDBC applications. and secures to be used on any platform. The JDBC-ODBC bridge driver enables a Java application to use any database that supports ODBC driver.

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

15 JDBC and JavaBeans . CLI native libraries are loaded on the server. The following figure shows the working of the JDBC-Net PureJava driver: 1A. The JDBC-Net Pure-Java driver consists of client and server portions. You can use the JDBC-Net Pure-Java driver over the Web while connecting applets with databases.Native-API Partly-Java Driver The JDBC-Net Pure-Java Driver The JDBC-Net Pure-Java driver is called the Type 3 driver. translates JDBC calls into database calls. which in turn. 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. When you use the JDBC-Net Pure-Java driver. The database calls are sent to the server portion of the JDBC-Net Pure-Java driver that forwards the request to the database.

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

You can create the front-end for an application that uses MS Access as back-end using any programming language. The following figure shows a two-tier database model: 1A. For example. where the client directly communicates with the server. the client layer provides the interface and logic to interact with the database. This connection in the two-tier database model remains active for the complete session of an application.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. even when the client and server are not exchanging information. In a two-tier database model. such as Java. MS Access supports two-tier database model. client and server. A connection is established between the client and server to enable point-to-point communication.17 JDBC and JavaBeans .

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. The middleware then transfers the data to the database server. The database-user interacts only with the client layer and has nothing to do with the middleware and server layer. The advantages of a three-tier database model are: Provides an abstraction layer. Provides a method to separate the responsibilities of the database developer and database user. JDBC and JavaBeans 1A. Reduces the bandwidth consumption. The client in the three-tier database model passes all the data to the middleware. Server: Consists of Database Management System (DBMS). On the other hand.Two-tier Database Model In a three-tier database model. The three-tier database model enables you to create the user-interface that is independent of the database used. the database-developer is concerned only with the server layer. a client communicates with the server through a middleware. which performs the business logic validation.18 .

The following figure shows a three-tier database model: Three-Tier Database Model 1A.19 JDBC and JavaBeans .

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

) • 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.Introducing JDBC Using JDBC API (Contd.21 JDBC and JavaBeans .

Introducing JDBC Using JDBC API (Contd.22 .) • 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.

©NIIT JDBC and JavaBeans Lesson 1A / Slide 12 of 36 1A. • The method call to use the the forName() method is: Class.) • Using the forName() method • The forName() method is available in the java.Introducing JDBC Using JDBC API (Contd.JdbcOdbcDriver"). • The forName() method loads the JDBC driver and registers the driver with the driver manager.forName("sun.lang.odbc.Class class.jdbc.23 JDBC and JavaBeans .

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

) • Setting System Property • Add the driver name to the jdbc.Introducing JDBC Using JDBC API (Contd.drivers system property to load a JDBC driver.odbc. • Use the –D command line option to set the system property on the command line.drivers=sun.25 JDBC and JavaBeans . • The command to set the system property is: java –Djdbc.jdbc.JdbcOdbcDriver SampleApplication ©NIIT JDBC and JavaBeans Lesson 1A / Slide 14 of 36 1A.

• The getConnection()method method has the following three forms: • Connection getConnection (String <url>) • Connection getConnection (String <url>. String <username>.) • Connecting to a Database • The DriverManager class provides the getConnection() method to create a Connection object.Introducing JDBC Using JDBC API (Contd. String <password>) • Connection getConnection (String <url>.Properties <properties>) ©NIIT JDBC and JavaBeans Lesson 1A / Slide 15 of 36 JDBC and JavaBeans 1A.26 .

) • 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.Introducing JDBC Using JDBC API (Contd.27 JDBC and JavaBeans . • 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.

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 .

executeQuery(str). Statement stmt = con.createStatement().29 JDBC and JavaBeans . • The code snippet to retrieve data from the authors table is: String str = "SELECT * FROM authors".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. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 18 of 36 1A. ResultSet rs = stmt.

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

executeUpdate(str).’ WHERE au_id='998-72-3568'". 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'". int count = stmt.createStatement().createStatement(). Statement stmt = con. • ©NIIT JDBC and JavaBeans Lesson 1A / Slide 20 of 36 1A.31 JDBC and JavaBeans .) • 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. Statement stmt = con.Introducing JDBC Using JDBC API (Contd.

Introducing JDBC Using JDBC API (Contd. stmt. Statement stmt=con." +"p_name VARCHAR(25). • The code snippet to create a table is: String str="CREATE TABLE MyProduct" +" (p_id INTEGER." +"unit_msr CHAR(6))".) • Creating a Table • The CREATE TABLE statement is used to create and define the structure of a table in a database. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 21 of 36 JDBC and JavaBeans 1A.execute(str).32 ." +"rate FLOAT.createStatement().

• DDL provides the DROP TABLE statement to drop a table from a database.Introducing JDBC Using JDBC API (Contd.execute(str).createStatement().) • Altering and Dropping a Table • DDL provides the ALTER statement to modify the definition of database object.33 JDBC and JavaBeans . • The code snippet to add a column to the MyProduct table is: String str="ALTER TABLE MyProduct " +"ADD quantity INTEGER". Statement stmt=con. • The code snippet to drop the MyProduct table from a database is: String str="DROP TABLE MyProduct".createStatement(). stmt. Statement stmt=con. stmt.execute(str). JDBC and JavaBeans Lesson 1A / Slide 22 of 36 ©NIIT 1A.

©NIIT JDBC and JavaBeans Lesson 1A / Slide 23 of 36 INSTRUCTOR NOTES Tell the students that java. You also need to explain how to create JDBC applications with the help of code snippets provided in this section. In this section. which is derived from the java.sql package. • You can catch the SQLException in a Java application using the try and catch exception handling block.sql package as described in the chapter.lang.Exception class. • SQLException getNextException(): Returns the next exception in the chain of exceptions. describe the steps involved in creating a JDBC application. After discussing the java. • The SQLException class contains various methods that provide error information.) • Handling SQL Exceptions • The java. briefly discuss the classes and interfaces in the java.sql package provides the SQLException class.sql package contains the classes and interfaces to develop JDBC applications. • String getSQLState(): Returns X/Open error code. these methods are: • int getErrorCode(): Returns the error code associated with the error occurred.sql packages. You need to use database drivers and the JDBC API while developing a Java application to retrieve or store data in a database.sql and the javax. The JDBC API classes and interfaces are available in the java.34 .Introducing JDBC Using JDBC API (Contd. The classes JDBC and JavaBeans 1A.

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. The javax. In addition. the java.sql package. such as establish and close a connection with a database.sql package is an extension to java. The java. The commonly used classes and interfaces in the JDBC API are: DriverManager class: Loads the driver for a database. java. and update data in a database.sql package contains JDBC APIs that use the Java programming language to access and store data in the data sources. The javax.sql package. write. 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. Statement interface: Enables you to execute SQL statements. retrieve data from a database.sql package 1A. The java.sql package is also referred as JDBC Optional Package API and enables you to communicate with the server side data sources.and interfaces perform a number of tasks.sql package enables you to read. SQLException class: Provides information about the exceptions that occur while interacting with databases. ResultSet interface: Represents the information retrieved from a database. All JDBC driver classes must implement the Driver interface. The javax.sql.sql and javax. Connection interface: Enables you to establish a connection between a Java application and a database.35 JDBC and JavaBeans . send a request to a database.sql package is the JDBC core API that is used to access and store client data sources.sql package contains JDBC APIs that use the Java programming language to access and store server-side data sources. To query a database and display the result using Java applications.0 Application Programming Interface (API) categorizes the API in two packages. Driver interface: Represents a database driver. The javax. and update the data stored in the data sources.

You can load the JDBC-ODBC Bridge driver using the following method call: Class. The forName() method loads the JDBC driver and registers the driver with the driver manager. The various features of javax.forName("<driver_name>").registerDriver(d). Using the registerDriver() Method You can create an instance of the Driver class to load a JDBC driver. The syntax to load a JDBC driver to access a database is: Class. You can register the JDBC-ODBC Bridge driver using the following method call to registerDriver() method: DriverManager.jdbc. Loading a Driver The first step to develop a JDBC application is to load and register the required driver using the driver manager.sql package are connection pooling.36 . You can use the following statement to create an instance of the Driver class: Driver d = new sun. Once you have created the Driver object.jdbc.odbc.odbc.JdbcOdbcDriver"). and rowsets.forName("sun. 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.JdbcOdbcDriver(). call the registerDriver() method to register it with the DriverManager. distributed transactions. JDBC and JavaBeans 1A. The syntax to declare an instance of the Driver class is: Driver d=new <driver name>.Class class.provides a DataSource interface that enables you to connect with the data sources on the server.lang.

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

the executeUpdate() method executes an SQL statement and number of rows affected in a database is stored in count. boolean execute(String str): Executes an SQL statement and returns a boolean value. 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. 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.execute(<SQL statement>). the int type variable. int count = stmt.BigDecimal JDBC and JavaBeans 1A.40 . stmt.Statement stmt = con. The corresponding Java data types are used to store the SQL data types that are returned as the result of SQL queries.math. 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.executeUpdate(<SQL statement>). The syntax to use the execute() methods is: Statement stmt = con.math. In the preceding syntax.BigDecimal DECIMAL java.createStatement().createStatement(). 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.

sql.Data TIME java.Timestamp 1A.sql.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.41 JDBC and JavaBeans .Time TIMESTAMP java.sql.

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. in Java applications to define or change the structure of database objects. state. contract) VALUES ('998-72-3568'. UPDATE. 'Salt Lake City'. The executeUpdate() method enables you to add rows in a table. Statement stmt = con. CREATE. The SELECT statement is executed using the executeQuery() method and returns the output in the form of a ResultSet object. executeQuery() method retrieves the details from authors tables for a particular city. and DROP. The result is stored in the ResultSet object. the condition to retrieve the rows is specified in the WHERE clause of the SELECT statement. au_lname. and DELETE.executeQuery(str). Statement stmt = con. You can use the following code snippet to insert a row in the authors table: String str = " INSERT INTO authors (au_id. in Java applications to modify the data stored in the database tables. ResultSet rs = stmt.executeQuery(str).'Albert'.createStatement().42 .createStatement(). str contains the SELECT statement that retrieves data from the authors table.'1')". au_fname. In the preceding code snippet.'. ALTER.'801 826-0752 67 Seventh Av. INSERT.You can use the DML statements.'UT'. Inserting Rows in a Table You can add rows in an existing table using the INSERT statement. 'Ringer'. JDBC and JavaBeans 1A. In the preceding code snippet. You can use the following code snippet to retrieve data from the authors table: String str = "SELECT * FROM authors". rs. You can also use the Data Definition Language(DDL) statements. address. city. You can use the following code snippet to retrieve selected rows from the authors table: String str = "SELECT * FROM authors WHERE city=’Oakland’". When you need to retrieve selected rows from a table. ResultSet rs = stmt.

executeUpdate(str).executeUpdate(str). Updating Rows in a Table You can modify the existing information in a table using the UPDATE statement.Statement stmt = con. In the preceding code snippet. Creating a Table You use the CREATE TABLE statement to create and define the structure of a table in a database." +"unit_msr CHAR(6))". int count = stmt.execute(str). str contains the DELETE statement that you need to send to a database. Statement stmt = con. You can use the following code snippet to modify a row in the authors table: String str = "UPDATE authors SET address='10932 Second Av. In the preceding code snippet. Statement stmt=con. int count = stmt.createStatement().' WHERE au_id='998-72-3568'".createStatement(). str contains the INSERT statement that you need to send to a database. stmt.createStatement(). executes the INSERT statement using the executeUpdate() method and returns the number of rows inserted in the table to the count variable. str contains the UPDATE statement that you need to send to a database.43 JDBC and JavaBeans .executeUpdate(str). Statement stmt = con." +"rate FLOAT. Deleting Rows from a Table You can delete existing information from a table using the DELETE statement. The Statement object executes this statement using the executeUpdate() method and returns the number of rows modified in the table to the count variable. 1A. int count = stmt. You can use the following code snippet in a Java application to create a table: String str="CREATE TABLE MyProduct" +" (p_id INTEGER. In the preceding code snippet.createStatement(). 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'". The object of the Statement interface." +"p_name VARCHAR(25). The Statement object executes this statement using the executeUpdate() method and returns the number of rows deleted from the table to the count variable. stmt.

As a result.createStatement().createStatement(). The SQLException class contains various methods that provide error information. 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". the str String contains the CREATE TABLE statement to create the MyProduct table. and add a constraint to a column. an error may give different error messages. You use the DROP TABLE statement to drop a table from a database. The methods in the SQLException class are: JDBC and JavaBeans 1A. The execute methods throw SQLException when any runtime error occurs while executing SQL statements. You use the ALTER TABLE statement to modify the structure of a table. you use this statement to add a new column in a table. You can use the following code snippet to drop the MyProduct table using a Java application: String str="DROP TABLE MyProduct". For example. stmt. SQL state: Is an X/OPEN error code that identifies the error. The X/OPEN error code is a standard message associated with an error that can identify the error across multiple databases. stmt. Statement stmt=con. 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. Various vendors provide different error messages to define same error.execute(str). The execute() method is used to process the CREATE TABLE statement. change the data type and width of an existing column. When you create JDBC applications you need to handle exceptions. You can catch the SQLException in a Java application using the try and catch exception handling block. which is derived from the java.sql package provides the SQLException class.Exception class. DDL provides the DROP statement to drop an object from a database. Statement stmt=con.44 . Altering and Dropping a Table DDL provides the ALTER statement to modify the definition of database object.In the preceding code snippet.lang. The SQLException class provides the following error information: Error message: Is a string that describes error. The error code is vendor-specific and depends upon database in use. Error code: Is an integer value that is associated with error.execute(str). Handling SQL Exceptions The java.

out. The sqlExceptionObject is an object of the SQLException class and is used to invoke the getErrorCode() method. String getSQLState(): Returns X/Open error code. } In the preceding code snippet. } catch(SQLException sqlExceptionObject) { System. Statement stmt = con.executeUpdate(str). 1A. SQLException getNextException(): Returns the next exception in the chain of exceptions. if the DELETE statement at runtime throws an SQLException then it is handled using the try catch block.getErrorCode()).out.createStatement().println("SQL Exception"+ sqlExceptionObject.45 JDBC and JavaBeans . You can use the following code snippet to catch SQLException: try { String str = "DELETE FROM authors WHERE au_id='998-72-3568'". int count = stmt.println("Display Error Code"). System.int getErrorCode(): Returns the error code associated with the error occurred.

Scrollable: Moves the result set cursor forward or backward through the result set.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. 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 . 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.

TYPE_SCROLL_INSENSITIVE TYPE_FORWARD_ONLY ©NIIT JDBC and JavaBeans Lesson 1A / Slide 25 of 36 1A.) • 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.Introducing JDBC Accessing Result Sets (Contd. Specifies that the cursor of the ResultSet object is scrollable and it does not reflect changes in the data made by other users.47 JDBC and JavaBeans . Specifies that the cursor of the ResultSet object moves in forward direction only from the first row to the last row.

) • 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.Introducing JDBC Accessing Result Sets (Contd. 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 .

Specifies that a ResultSet object should be closed after data is committed to the database.49 JDBC and JavaBeans . CLOSE_CURSORS_AT_COMMIT ©NIIT JDBC and JavaBeans Lesson 1A / Slide 27 of 36 1A.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.

int) ©NIIT JDBC and JavaBeans Lesson 1A / Slide 28 of 36 JDBC and JavaBeans 1A. int.50 .Introducing JDBC Accessing Result Sets (Contd. int) Statement createStatement(int.) • The createStatement() method has the following three overloaded forms: • • • Statement createStatement() Statement createStatement(int.

Determines whether the result set cursor points to the first row of the result set.) • 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.Introducing JDBC Accessing Result Sets (Contd. 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. JDBC and JavaBeans Lesson 1A / Slide 29 of 36 1A. Shifts the control of a result set cursor before the first row of the result set.51 JDBC and JavaBeans . Determines whether the result set cursor points to the last row of the result set.

relative to the row number that you specify as a parameter. 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.52 .) 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.Introducing JDBC Accessing Result Sets (Contd. Shifts the control of a result set cursor to the previous row of the result set.) • The methods of ResultSet interface (Contd. JDBC and JavaBeans Lesson 1A / Slide 30 of 36 JDBC and JavaBeans 1A.

The cursor in the ResultSet object initially points before the first row.Introducing JDBC Accessing Result Sets (Contd. You cannot update the default ResultSet object. 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. A ResultSet object maintains a cursor that enables you to move through the rows stored in a ResultSet object. 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.) • • JDBC allows you to create an updatable result set that enables you to modify the rows in the result set. As a result. Tell the students that there are various types of result sets to store the data retrieved from a database. Inserts a row in the current ResultSet object and the underlying database table. Updates the specified column with the given int value. Updates the specified column with the given string value. the ResultSet object maintains a cursor that moves in the forward direction only. it moves from the first row to the last row in the ResultSet. Deletes a row from the current ResultSet object and the underlying database table. 1A. 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. By default. You need to explain the procedure to create different types of result sets as discussed in the chapter.53 JDBC and JavaBeans .

Specifies that the cursor of the ResultSet object is scrollable and it does not reflect changes in the data made by other users. Forward only: Allows you to move the result set cursor from first row to last row in forward direction only.Types of Result Sets You can create various types of ResultSet objects to store the output returned by a database after executing SQL statements. 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. The createStatement() accepts ResultSet fields as parameters to create different types of the ResultSet objects. JDBC and JavaBeans 1A. You can specify the type of a ResultSet object using the createStatement() method of the Connection interface. Scrollable: Allows you to move the result set cursor forward or backward through the result set. Various types of ResultSet objects are: Read only: Allows you to only read the rows in a ResultSet object. Specifies that the cursor of the ResultSet object moves in forward direction only from the first row to the last row. Updatable: Allows you to update the result set rows retrieved from a database table. 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.54 .

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. Statement createStatement(int. Statement createStatement(int. The following table lists the methods of the ResultSet interface: 1A. the result set is closed after committing data to the database. This method creates a ResultSet object with the given type.ResultSet Fields CONCUR_UPDATABLE Description Specifies the concurrency mode that allows you to update the ResultSet object. This parameter indicates whether or not. In addition to the ResultSet types and the concurrency mode. this method accepts a third parameter. The second parameter indicates the concurrency mode for the result set that determines whether the data in result set can be updated. int. The following are three overloaded forms of the createStatement() method: Statement createStatement(): Does not accept any parameter. CLOSE_CURSORS_AT_COMMIT The createStatement() method is an overloaded method that has three prototypes. int): Accepts two parameters. This method creates a ResultSet object with the given type and concurrency. Methods of ResultSet Interface The ResultSet interface contains various methods that enable you to move the cursor through the result set. and state. concurrency. The first parameter indicates the ResultSet type that determines whether or not. a result set cursor can move backward.55 JDBC and JavaBeans . int): Accepts three parameters. Specifies that a ResultSet object should be closed after data is committed to the database. This method creates a default ResultSet object that only allows forward scrolling.

Shifts the control of a result set cursor. Shifts the control of a result set cursor before the first row of the result set.TYPE_SCROLL_INSENSITIVE. You can create a scrollable result set that scrolls backward or forward through the rows in the result set. ResultSet rs=stmt. This method accepts either a positive or a negative value as a parameter.executeQuery ("SELECT * FROM authors"). ResultSet.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. Shifts the control of a result set cursor to the previous row of the result set. You can use the following code snippet to create a read only scrollable result set: Statement stmt = con. Determines whether the result set cursor points to the first 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 before the first row of the result set. Shifts the control of a result set cursor to the last row of the result set. You can determine the location of the result set cursor using the methods in the ResultSet interface.CONCUR_READ_ONLY). 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 row number that you specify as a parameter.createStatement(ResultSet. Determines whether the result set cursor points to the last row of the result set. forward or backward.56 . 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. relative to the row number that you specify as a parameter.

rs is the ResultSet object that calls the isBeforeFirst() method. in the result set using the methods in the ResultSet interface. If you want to move to any particular row of a result set.absolute(4). such as first or last. void insertRow() void deleteRow() 1A.getString(3)).out. 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.isBeforeFirst()==true) System. int rowcount = rs. you can use the absolute() method. Inserts a row in the current ResultSet object and the underlying database table.println("Using absolute() method").if(rs.57 JDBC and JavaBeans . rs.println("rowNum should be 4 " + rowcount). you can move the result set cursor to the last row in the result set using the last() method. Similarly.absolute(-2). " + rs. if the result set cursor is at the first row and you want to scroll to the fourth row. You can use the following code snippet to move the result set cursor to the first row in the result set: if(rs. specify rs. as shown in the following code snippet: System. 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. In the preceding code.println("Result set cursor is before the first row in the result set"). For example.first()==true) System.getString(1) + ".getRow().getString(2)+ ". JDBC allows you to create an updatable result set that enables you to modify the rows in the result set. You can move to a particular row. rs is the ResultSet object that calls the first() method. Deletes a row from the current ResultSet object and the underlying database table. For example. System. to set the cursor to the row above the last row.println(rs.out.out. In the preceding code snippet.out. " + rs. you should enter 4 as a parameter when you call the absolute() method.

createStatement(). state FROM authors WHERE au_id='893-72-1158' "). ResultSet rs = stmt.sql. Updates the specified column with the given int value.sql. You can use the following code to create an updatable ResultSet using the type 4 JDBC driver: import java.*.updateRow(). rs. the row is retrieved from the authors table where author id is 893-72-1158. rs. import javax. You can use the following code snippet to modify the author information using the updatable result set: Statement stmt = con.next(). the value in the state column is changed to NY and the value in the city column is changed to Columbia.updateString("city".Method void updateString() void updateInt() Description Updates the specified column with the given string value.naming. stmt = con.updateString("state". INSTRUCTOR NOTES Additional Input Creating updatable result set: The type 4 JDBC driver can be used to create updatable ResultSet. import javax.com/downloads. "Columbia").DataSource. In the preceding code snippet.createStatement(ResultSet.*. It can be downloaded from.microsoft. http://www. "NY").TYPE_SCROLL_SENSITIVE. public class UpdatableResultset { public static void main(String args[]) { try { //Initialize and load the JDBC-ODBC bridge driver JDBC and JavaBeans 1A. city.sql. In the retrieved row.CONCUR_UPDATABLE). rs. rs.*. ResultSet.58 . import javax.executeQuery("SELECT au_id.

//Retrieve author information ResultSet rs = stmt. " + rs. } catch(Exception e) { System.authors where au_id='893-72-1158' ").dbo."").createStatement(ResultSet."administrator". rs. con. ResultSet.} Class.println(rs.close().getString(1) + ". while(rs. the author information is modified using the Updatable resultset. rs. The value in the state column is changed to OR and value in the city column is changed to Corvallis.TYPE_SCROLL_SENSITIVE.updateString("state".microsoft."").SQLServerD river").createStatement().getString(3)).city. } } In the preceding code.getConnection("jdbc:microsoft:sqlserver: //dc06:1433".sqlserver.city.CONCUR_UPDATABLE). con = DriverManager.updateString("city". state from pubs.createStatement().next().jdbc.executeQuery("Select au_id. " + rs.println("Error " + e)."administrator".forName("com. //Update data rs. "OR").getConnection("jdbc:microsoft:sqlserver: //dc06:1433". //Close a data source connection con.close().getString(2) + ". rs.authors where au_id='893-72-1158' ").59 JDBC and JavaBeans . //Establish a connection with a data source Connection con = DriverManager. state from pubs.executeQuery("Select au_id. stmt = con.updateRow().next()) System. "Corvallis"). rs = stmt. //Create an Updatable resultset stmt = con.out. //Create a Statement object Statement stmt = con.dbo.out. 1A.

60 . and state) about the authors who are living in the city where the city name begins with the letter “O”.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. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 32 of 36 JDBC and JavaBeans 1A. address. name. city.

Compile and execute the application.Introducing JDBC Demonstration-Creating a JDBC Application to Query a Database (Contd. 3. Explain the steps to create DSN as discussed in the section. Code the application.61 JDBC and JavaBeans . you can explain the application to be demonstrated. name. and state) about the authors who are living in the city where the city name begins with the letter “O”.) • Solution • JDBC-ODBC Bridge driver is to be used for creating the application. Create a Data Source Name (DSN). perform the following tasks: 1. To solve the above problem. 2. Compile and run the Authorsinfo. Problem Statement Create an application to retrieve information (author id. address. 1A. After creating DSN. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 33 of 36 INSTRUCTOR NOTES Start this section by explaining the purpose of creating DSN.java code file to execute the application. city.

Create a Data Source Name (DSN). Compile and execute the application. The following figure shows the ODBC Data Source Administrator dialog box: ODBC Data Source Administrator Dialog Box JDBC and JavaBeans 1A.62 . To open the ODBC Data Source Administrator dialog box. To access the options that enable you to configure the administrative settings. double-click the Administrative Tools icon. double-click the Data sources (ODBC) icon. Code the application. Specifying the connection details for a DSN c. you need to perform following steps: a. 2. 3. 3. Testing the created DSN a. Selecting the required driver for a DSN b. 1. To select the required driver for the DSN. To solve the above problem. you need to first open the Control Panel window. perform the following tasks: 1. Select the Start Settings Control Panel command to open the Control Panel window.Solution JDBC-ODBC Bridge driver is to be used for creating the application. Create a DSN To create a DSN. Selecting the required driver for a DSN 1. 2.

4. To select a driver for creating a DSN. To connect to SQL Server 2000. 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. from the list of drivers. as shown in the following figure: Create New Data Source Dialog Box 6. click the Finish button. To create a DSN. click the Add button. you need to specify the connection details for a DSN. 5. 1.63 JDBC and JavaBeans . b. select the SQL Server option from the Name list box in the Create New Data Source dialog box. Specifying the Connection Details for a DSN After you select the required driver for a DSN. To complete the task of selecting the driver for the creating a DSN.

To indicate how the SQL Server should authenticate a login ID. JDBC and JavaBeans 1A. type the user name in the Login ID text box and the password in the Password text box and click the Next button. 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.Create a New Data Source to SQL Server Dialog Box 2. To indicate the user name and password to connect to the database.64 . 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. 3.

select English from the drop down list and click the Finish button. To select the language for the system messages. To indicate the language for the system messages. 7. The ODBC Microsoft SQL Server 1A. select the Change the default database to option. select the Change the language of SQL Server system messages to option. To enable the database drop-down list.65 JDBC and JavaBeans .5. as shown in the following figure: Changing the SQL Server System Messages Language 8. To select the required database select the name of the database from the drop-down list box and click the Next button. as shown in the following figure: Selecting a Default Database 6.

To test the created DSN for the connection with the database. 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. Testing the created DSN 1.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. click the Test Data Source button.66 .

3.67 JDBC and JavaBeans . 4. The following figure shows the ODBC Data Source Administrator dialog box: 1A. To save the configuration settings for the new data source. 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.SQL Server ODBC Data Source Test Dialog Box 2. To return to the ODBC Microsoft SQL Server Setup dialog box. click the OK button. click the OK button. To verify that the DSN is created.

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

System.out. } } } The preceding code is saved as an AuthorsInfo.println(city).print(fname+"\t"). System.out.close().getString("au_id"). System.out. String lname=rs.java file. 3.executeQuery(str).print(fname+"\t\t").print(id+"\t").getString("au_fname").getString("city").length() <=7) System.println("Author ID\tFirst Name\tLast Name\tCity").out.print(lname+"\t"). the two tabs are used to specify the position to display the next column in the ResultSet*/ if (fname.println("Error occurred").length() <=7) System. } con. If the number of characters in a data value are less than or equal to 7.out.print(lname+"\t\t").out./*Create a Statement object to process the SELECT statement*/ Statement stmt=con.java The command to execute the AuthorsInfo application is: java AuthorsInfo 1A. else System. System. /*Display the result*/ while (rs.69 JDBC and JavaBeans .out.createStatement(). Compile and Execute the Application The command to compile the AuthorsInfo application is: javac AuthorsInfo. String fname=rs.println("Error:"+ex). /*Use tab to format the output. } catch(Exception ex) { System.out. /*Execute the SELECT SQL statement*/ ResultSet rs=stmt. String city=rs.next()) { String id=rs. else System.getString("au_lname").out. if (lname.

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

This layer acts as an interface between a Java application and a database.71 JDBC and JavaBeans . 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. such as an SQL Server driver. The JDBC driver manager manages various JDBC drivers. which enables a Java application to connect to a database. • JDBC driver layer: Contains a driver. 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.SUMMARY Introducing JDBC Summary In this lesson.

Two ways to load and register a driver programmatically are: • Using the Class.Introducing JDBC Summary (Contd. You can load a driver and register it with the driver manager either programmatically or manually.sql and javax.sql packages. The classes and interfaces of the JDBC API are defined in the java.72 .forName() method • Using the registerDriver() method • • • • ©NIIT JDBC and JavaBeans Lesson 1A / Slide 35 of 36 JDBC and JavaBeans 1A.) • 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.

sql packages.73 JDBC and JavaBeans .sql and javax.) • 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.Introducing JDBC Summary (Contd. Two ways to load and register a driver programmatically are: • Using the Class. The classes and interfaces of the JDBC API are defined in the java. You can load a driver and register it with the driver manager either programmatically or manually.forName() method • Using the registerDriver() method • • • • ©NIIT JDBC and JavaBeans Lesson 1A / Slide 35 of 36 1A.

74 .drivers system property to load and register a JDBC driver manually. update. and forward only. A Statement object sends requests to and retrieves results from a database. and delete data from a table using the DML statements in Java applications. 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. You can insert. You can create various types of ResultSet objects such as read only. This layer acts as an interface between a Java application and a database. and drop tables from a database using the DDL statements in Java applications.) • • • • • • • You can add the driver name to the jdbc. A Connection object establishes a connection between a Java application and a database. such as an SQL Server driver. 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 JDBC driver manager manages various JDBC drivers. which enables a Java application to connect to a database. You can create. A ResultSet object stores the result retrieved from a database when a SELECT statement is executed. JDBC and JavaBeans 1A. updatable. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 36 of 36 In this lesson. JDBC driver layer: Contains a driver. alter. The JDBC driver is software that a Java application uses to access a database.Introducing JDBC Summary (Contd.

You can create.sql packages.sql and javax.75 JDBC and JavaBeans . You can load a driver and register it with the driver manager either programmatically or manually. A Statement object sends requests to and retrieves results from a database. and drop tables from a database using the DDL statements in Java applications. and delete data from a table using the DML statements in Java applications. 1A.forName() method Using the registerDriver() method You can add the driver name to the jdbc. You can insert. updatable. update. A ResultSet object stores the result retrieved from a database when a SELECT statement is executed. and forward only.drivers system property to load and register a JDBC driver manually. Two ways to load and register a driver programmatically are: Using the Class. A Connection object establishes a connection between a Java application and a database. alter. You can create various types of ResultSet objects such as read only.The classes and interfaces of the JDBC API are defined in the java.

76 .JDBC and JavaBeans 1A.

Sign up to vote on this title
UsefulNot useful