You are on page 1of 29

Chapter 1 [Introduction to SQL] SQL Introduction o What is SQL?

? o SQL DDL o SQL DML o Common terms used in SQL commands o SQL reference o create, update, delete and select table syntaxes o Normalization First Normal Form Second Normal Form Third Normal Form Fourth Normal Form Fifth Normal Form BCNF Form DKNF o Example o 12 CODD rules Introduction to DBMS Chapter 2 [Introduction to JDBC] How to interact with DB? o Problem and Advantages About ODBC o What is ODBC o ODBC Architecture o Advantages

What for JDBC?


What is JDBC? About X/Open Group JDBC API o JDBC Core API o JDBC Ext or Optional API (javax.sql package) JDBC Architecture & About JDBC Drivers Different Types of JDBC Drivers o Type 1 Architecture Advantages Disadvantages Where to use? Examples of this type of driver o JdbcOdbcDriver from Sun o Setting environment to use this driver Software PATH CLASSPATH How to use this driver o Type 2 Architecture Advantages Disadvantages

Where to use? Examples of this type of driver o OCI 8 from Oracle o Setting environment to use this driver Software PATH CLASSPATH How to use this driver Architecture Advantages Disadvantages Where to use? Examples of this type of driver o IDS Driver from IDS o Setting environment to use this driver Software PATH CLASSPATH How to use this driver Achitecture Advantages Disadvantages Where to use? Examples of this type of driver o JdbcOdbcDriver from Sun o Setting environment to use this driver Software PATH CLASSPATH How to use this driver

Type 3

Type 4

Chapter 3 [JDBC Core API] JDBC Core API Overview with Class Diagram Using Statement to o Create table o Insert record o updating data Sample applications using all Types of drivers Using ResultSet to retrieve data from DB o Sample application Using DatabaseMetadata o With samples Using ResultSetMetadata o With samples Explanation on how the query given is executed in DB o Different phases About PreparedStatement o Context where to use o Advantages o Differences between Statement and PreparedStatement

Introduction to Procedures & functions CallableStatement o Sample Applications on Procedure with in argument Out argument in out argument Chapter 4 [JDBC 2.0] Batch Updates o Usage, Advantages o Sample Different types of ResultSet o Updatable ResultSet o Scrollable ResultSet Sensitive In sensitive RowSets o Example o Context to use RowSet Listener Using new Data Types support o BLOB o CLOB o REF o Object With samples Chapter 5 [JDBC Exp API] JDBC Ext API Overview JDBC Connection Pooling o Concept o Architecture o Advantages o Sample Chapter 6 [JDBC 3.0] Save points Cursors Parameter Metadata Chapter 7 [Transactions] Transactions o What is Transaction? o ACID properties desc o About Resource, Resource Managers o Types of Transactions Based on Number of Resources Local TX Distributed TX Based on Transaction Contexts Flat TX

Nested TX Chained TX o Sample application on Local Flat TX Local Nested TX Local Chained TX Primary Key generation strategy o Using Sequence o Primary key generator Using TX Isolation level Ser Sample application Chapter 8 [JDBC FAQ] JDBC FAQ Chapter 9 [javax.sql package]

Chapter #1 SQL Introduction

Introduction to SQL
SQL is a standard computer language for accessing and manipulating databases. SQL language mainly consists of 3 types of paradigms DDL (Data Definition Language) DML (Data Manipulation Language) DCL (Data Control Language)

SQL is the American National Standards Institute (ANSI) language for talking to Databases (though there are many additions to ANSI SQL). Some people pronounce it ess-que-ell, but I prefer to say it like sequel, since I can say it faster. Simply put SQL is a way of asking questions, or giving orders, to a database. A database is just a collection of information. I'm a fan of examples, so here's a (not-so) hypothetical situation: You keep a pad of paper next to the telephone for writing down people who call, and new phone numbers. You want to know how many times the school has called you this month. So you flip through the stack of paper and pull out all the pages with the school and this month on it. Your count them. Your stack of paper is a database. You are searching and counting is a query. Your database works for you. But if you suddenly hire a call center, and need to find out how many times your office called a prospect, you'll probably want to move to a SQL database. The biggest advantage of SQL is that you don't have to go through the stack of papers to find information you just need to know how to ask the question. And the question is always asked the same way:

select what you want to know from what stack of paper where something is on the page Not to complicated. The above example would read like this select count(when) from phonecalls where caller like '%school%' and date > now() - interval 1 months What is SQL? SQL stands for Structured Query Language SQL allows you to access a database SQL is ANSI standard computer language SQL can execute queries against a database SQL can retrieve data from a database L can insert new records in a database SQL can delete records from a database SQL can update records in a database SQL is easy to learn

SQL DDL The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted. We can also define indexes (keys), specify links between tables, and impose constraints between database tables. The most important DDL statements in SQL are: CREATE TABLE - creates a new database table ALTER TABLE - alters (changes) a database table DROP TABLE - deletes a database table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index

SQL DML SQL (Structured Query Language) is syntax for executing queries. But the SQL language also includes syntax to update, insert, and delete records. These query and update commands together form the Data Manipulation Language (DML) part of SQL: 1. 2. 3. 4. SELECT - extracts data from a database table UPDATE - updates data in a database table DELETE - deletes data from a database table INSERT INTO - inserts new data into a database table

Common terms used in SQL commands Primary Key (PK) attributes - uniquely identifies each tuple in the relation with no redundant

Foreign Key (FK) Composite Key Candidate Key (CK) Alternate Key (AK) Super Key redundant key attributes Prime Attribute Secondary Key Search Keys

- an attribute that is a PK in another relation - a PK consisting of multiple attributes - a set of attributes that can be used as a PK - a candidate key not designed as a PK - a set of attributes that includes a CK and may include - any attribute that belongs to a CK - an attribute that is used as an index - An attribute used in a query

SQL reference create table syntax create table table_name (column_name1 data_type1, column_name2 data_type2, , [ CONSTRAINT constraint_name CONSTRAINT_TYPE constraint_condition, ]); update statement syntax update table_expression_clause set_clause where_clause select statement syntax SELECT * | column_names_list FROM table_name WHERE_clause group_by_clause | order_byclause; delete statement syntax delete FROM table_expression_clause WHERE_clause; insert statement syntax insert into table_expression_clause (column1, column2, ) values_clause Normalization Normalization is the process of non-loss decomposition of the database into tables so as to minimize the data redundancy and inconsistencies in the database. We have to consider various constraints on the database so as to convert it into standard form viz. Integrity constraints and dependencies. Normalization is achieved through the series of steps. These steps are called normal forms. There are various normal forms like 1NF, 2NF and 3NF. Generally database normalized at 3NF serves the purpose, but for complex database representations, more advance level of normalizations, viz. 4NF, BCNF, DKNF etc is done. The database in one normal form is by default in previous normal forms. E.g. if it is in 3NF, it must be in 1NF and 2NF.
The normalization process, as first proposed by Codd (1972), takes a relation schema through a series of tests to "certify" whether or not it belongs to a certain normal form. Initially, Codd proposed three normal forms, which he called first, second, and third normal form. A stronger definition of 3NF was proposed later by Boyce and Codd and is known as Boyce-Codd normal form (BCNF). All these normal forms are based on the functional dependencies among the attributes of a relation. Later, a fourth normal form (4NF) and a fifth normal form (5NF) were proposed, based on the concepts or multi-valued dependencies and join dependencies, respectively.

First Normal Form: A relation is in first normal form if it does not contain any repeating values or groups. Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).

Second Normal Form: A relation is in second normal form if it is in 1NF and all non-key attributes are fully functional dependent on the primary key. Remove subsets of data that apply to multiple rows of a table and place them in separate tables. Create relationships between these new tables and their predecessors through the use of foreign keys.

Third Normal Form: A relation is in third normal form if it is in 2NF and every attribute is independent of all other non-key attributes. Remove columns that are not dependent upon the primary key. BCNF (Boyce-Codd Normal Form): A relation is in BCNF is if and only if every determinant is a candidate key. (A candidate is any attribute on which some other attribute is (fully) functionally dependent. Fourth normal form (4NF): A relation is in 4NF if it has no multi-valued dependencies.

Finally we have Fifth Normal Form (5 NF): In some cases there may be no losses join decomposition into two relation schemas but there may be a losses join decomposition into more than two relation schemas. These cases are handled by the join dependency and fifth normal form, and its important to note that these cases occur very rarely and are difficult to detect in practice. We can also always define stricter forms that take into account additional types of dependencies and constraints. The idea behind domain-key normal form is to specify, (theoretically, at least) the "ultimate normal form" that takes into account all possible dependencies and constraints. A relation is said to be in DKNF if all constraints and dependencies that should hold on the relation can be enforced simply by enforcing the domain constraints and the key constraints specified on the relation. For a relation in DKNF, it becomes very straightforward to enforce the constraints by simply checking that each attribute value in a tuple is of the appropriate domain and that every key constraint on the relation is enforced. However, it seems unlikely that complex constraints can be included in a DKNF relation; hence, its practical utility is limited. Consider a following table structure: Stud_no Stud_name Stud_addr teacher_code Sub_code

Sub_name Sub_teacher In the above table definition, the attribute groups Sub_code, Sub_name represents repeatable group as one student can take many subjects, so that information is repeated for the same student. We can convert above schema into 1NF by separating repeating columns (multi-valued attributes) into separate subject table. Student Stud_no Stud_name Stud_addr Student_subject Stud_no (CPK) Sub_code (CPK) Sub_name teacher_code Sub_teacher

In above schema the attribute Sub_name is not fully functionally dependant on composite key (Stud_no+Sub_code) of Student_subject table. So we can achieve 2NF by separating the attributes not fully functionally dependant on primary key into separate tables e.g. Student Stud_no (PK) Stud_name Stud_addr Student_subject Stud_no (FK) Sub_code (FK) teacher_code Sub_teacher Subject Sub_code (PK) Sub_name

In the above schema, the attribute Sub_teacher, which represents teacher for that subject, can be derived from that table itself looking at the two columns Sub_code and teacher_code. So we can achieve 3NF by removing such attribute, which is independent of non-key attributes. For ex: Student Stud_no Stud_name Stud_addr Student_subject Stud_no Sub_code teacher_code Subject Sub_code Sub_name

In the above schema, the attribute teacher_code represents the teacher for particular subject. This attribute is not the candidate key for the primary key of the table. We need to have one separate table called sub_teacher. The above normalization is called BCNF (Boyce/Codd Normal form) e.g. Student Stud_no Stud_name Stud_addr Student_subject Stud_no Sub_code Subject Sub_code Sub_name Sub_teacher Sub_code teacher_code

BCNF is improved form of 3NF. Consider the schema where in students understanding in each subject is mentioned as one of the best, average, poor. The table looks somewhat like this:

Student_subject Stud_no Sub_code Sub_interest In addition to above normalization levels, we also have other levels viz. 4NF, 5NF etc. which are complex are not applied in normal situations. DKNF (Domain Key Normal Form) Exercise: Following is the un-normalized database; normalize it up to BCNF through 1NF, 2NF, 3NF. Following is structure of order table: Order Order_No. Order_date Customer_no Item_no Item_name Qty_ordered Rate_per_unit Item_value (Item_value can be calculated using Qty_ordered * Rate_per_unit) 12 CODD Rules Rule 0: For any system to be called as RDBMS, it must be able to manage database entirely through its relational capabilities. Rule 1: All information in a RDBMS is represented explicitly in exactly one way, by value in the table. According to this rule anything that does not exist in a table in the database does not exist at all. Rule 2: Each and every datum is logically accessible through a combination of table name, column name, and primary key value. Rule 3: Inapplicable or missing information can be represented through null values. Rule 4: The description of the database is held in the same way as ordinary data that is in tables and columns and is accessible to authorized users. Rule 5: There must be at least one language which is comprehensive in supporting data definition, view definition, data manipulation, integrity constraints, authorization, and transaction control. Rule 6: All views that are theoretically updatable are updatable by the system. Rule 7: The capability of handling a base or a derived table as a single operand applies not only to the retrieval of data but also to the insertion, update and deletion of data. Rule 8: Application programs and terminal activity remain logically unimpaired whenever any changes are made in the storage representation or access method. Rule 9: Application programs and terminal activity remain logically unimpaired when information preserving changes of any kind that theoretically permit unimpairment are made to the base tables. Rule 10: All integrity constraints must be definable in the data sub language and storable in the catalogue, not in the application program. Rule 11: The system must have a data sub-language which can support distributed databases without impairing application programs or terminal activities. Rule 12: If the system has a low-level language this language cannot be used to bypass the integrity rules and constraints expressed in the higher level relational language.

Here I am giving example on creating database for an institute maintenance


project
Example #1 create table course_master (course_id varchar2(10), cname varchar2(100) NOT NULL, content varchar2(500), CONSTRAINT course_pk PRIMARY KEY(course_id)); #2 create table counseling_master ( counsel_id varchar2(10), counsel_date date NOT NULL, sname varchar2(100) NOT NULL, address varchar2(100) NOT NULL, email varchar2(20) NOT NULL, phone varchar2(15), timings_prefered time, CONSTRAINT counsel_pk PRIMARY KEY (counsel_id) ); #3 create table course_counseling( course_id varchar2(10) REFERENCES course_master(course_id), counsel_id varchar2(10) REFERENCES counseling_master(counsel_id) ); #4 create table registration_master ( stud_id varchar2(10), counsel_id varchar2(10), CONSTRAINT reg_pk PRIMARY KEY(stud_id), CONSTRAINT reg_counsel_fk counseling_master(counsel_id) ); #5 create table batch_master( batch_id varchar2(10), course_id varchar2(10), start_date date NOT NULL, faculty_name varchar2(50) NOT NULL, FOREIGN KEY(counsel_id) REFERENCES

duration number, track varchar2(2), CONSTRAINT batch_pk PRIMARY KEY(batch_id, course_id) ); #6 create table batch_students( batch_id varchar2(10), stud_id varchar2(10), CONSTRAINT batch_students_pk PRIMARY KEY(batch_id, stud_id) ); #7 create table student_fee( stud_id varchar2(10), total_fee number NOT NULL, due_amt number, CONSTRAINT stud_fee_pk FOREIGN KEY(stud_id) REFERENCES registration_master(stud_id) ); #8 create table receipts_master( receipt_id varchar2(10), rdate date NOT NULL, amt number NOT NULL, stud_id varchar2(10), CONSTRAINT receipt_pk PRIMARY KEY(receipt_id), CONSTRAINT receipt_stud_fk registration_master(stud_id) ); Introduction to DBMS A database-management system (DBMS) consists of a collection of interrelated data and a set of programs to access those data. The collection of data usually referred to as the database. The primary goal of DBMS is to provide an environment that is both convenient and efficient to use in retrieving and storing database information. Database systems are designed to manage large bodies of information. The DBMS has been introduced to overcome various difficulties that come into existence by using traditional file-processing system. Some of the difficulties are: 1) 2) 3) 4) 5) 6) 7) Data redundancy and inconsistency. Difficulty in accessing data. Data isolation Integrity problems Atomicity problems Concurrent access anomalies Security problems FOREIGN KEY(stud_id) REFERENCES

Chapter 2 [Introduction to JDBC]

How to Interact with DB?


Generally every DB vendor provides a User Interface through which we can easily execute SQL querys and get the result (For example Oracle Query Manager for Oracle, and TOAD (www.quest.com) tool common to all the databases). And these tools will help DB developers to create database. But as a programmer we want to interact with the DB dynamically to execute some SQL queries from our application (Any application like C, C++, JAVA etc), and for this requirement DB vendors provide some Native Libraries (Vendor Specific) using this we can interact with the DB i.e. If you want to execute some queries on Oracle DB, oracle vendor provides an OCI (Oracle Call Interface) Libraries to perform the same. Problem Application becomes DB Specific, if you want to change your DB you need to change your applications parameters which are required to connect to DB, and it is a risk on our application. (Since we know writing a new application is faster & easier than modifying an existing application)

Advantages Fast access to DB All individual features provided by the DB can be used

About ODBC
What is ODBC ODBC (Open Database Connectivity) is an ISV (Independent software vendor product) composes of native API to connect to different databases through via a single API called ODBC. Open Database Connectivity (ODBC) is an SQL oriented application programming interface developed by in collaboration with IBM and some other database vendors. Oracle ODBC ODBC comes with Microsoft products and with all databases on Windows OS. ODBC Architecture Front End Application
ODBC API

SP API

Oracle

SQL server ODBC Sybase ODBC

SP API

SQL server

C function calls Oracle DSN My DSN SQL Server DSN Sybase DSN Our DSN

SP API

Sybase

Oracle ODBC SQL server ODBC Sybase ODBC

Oracle
SQL Server

Sybase

Advantages Single API (Protocol) is used to interact with any DB Switching from one DB to another is easy Doesnt require any modifications in the Application when you want to shift from one DB to other. What for JDBC? As we have studied about ODBC and is advantages and came to know that it provides a common API to interact with any DB which has an ODBC Service Providers Implementation written in Native API that can be used in your applications. If an application wants to interact with the DB then the options which have been explained up to now in this book are: 1. Using Native Libraries given by the DB vendor 2. Using ODBC API And we have listed there Advantages and Disadvantages. But if the application is a JAVA application then the above given options are not recommended to be used due to the following reasons 1. Native Libraries given by DB vendor a. Application becomes vendor dependent and b. The application has to use JNI to interact with Native Lib which may cause serious problem for Platform Independency in our applications. 2. And the second option given was using ODBC API which can solve the 1.a problem but again this ODBC API is also a Native API, so we have to use JNI in our Java applications which lead to the 1.b described problem. And the answer for these problems is JDBC (Java Data Base Connectivity) which provides a common Java API to interact with any DB. What is JDBC As explained above JDBC standards for Java Data Base Connectivity. It is a specification given by Sun Microsystems and standards followed by X/Open SAG (SQL Access Group) CLI (Call Level Interface) to interact with the DB.

About X/Open Group Founded in 1984, X/Open is a worldwide, independent company dedicated to bringing the benefits of open computer systems to market. The company markets products and services to computer system buyers, system suppliers, software developers, and standards organizations. X/Open SQL Access Group, is composed of representatives from AT&T, Borland, Computer Associates, Fulcrum, Hitachi, IBM, Information Builders, Informix, INTERSOLV, Microsoft Corp., Oracle Corporation, Progress, Sybase and Visigenic Software. The X/Open Data Management Working Group was formed in 1986, and has since completed specifications for the X/Open Common Applications Environment (CAE) SQL syntax and semantics. The SQL Access Group started in 1989, and is best known for developing the standard SQL Call Level Interface (SQL/CLI), which formed the basis for Microsoft Corp.'s highly-successful Open Database Connectivity (ODBC) architecture and products. The combined group's mission is to provide developers with a common application programming interface (API) standard, which will ensure application compatibility, irrespective of vendor, platform or database. The JDBC API lets you invoke SQL commands from Java programing language methods. The JDBC API provides database-independent connectivity between the JAVA Applications and a wide range of tabular data bases. JDBC technology allows an application component provider to: Perform connection and authentication to a database server Manage transactions Moves SQL statements to a database engine for preprocessing and execution Executes stored procedures Inspects and modifies the results from SELECT statements JDBC API JDBC API is divided into two parts 1. JDBC Core API 2. JDBC Extension or Optional API JDBC Core API (java.sql package) This part of API deals with the following futures 1. Establish a connection to a DB 2. Getting DB Details 3. Getting Driver Details 4. maintaining Local Transaction 5. executing querys 6. getting results (ResultSet) 7. preparing pre-compiled SQL querys and executing 8. executing procedures & functions JDBC Ext OR Optional API (javax.sql package) This part of API deals with the following futures 1. Resource Objects with Distributed Transaction Management support 2. Connection Pooling.

These two parts of Specification are the part of J2SE and are inherited into J2EE i.e. this specification API can be used with all the components given under J2SE and J2EE. JDBC Architecture:

P A PI

JDBC Application JDB C API S JDBC Driver P A PI


MS SQL Server DB

SP AP I
Sybase DB

Oracle DB

In the above show archetecture diagram the JDBC Driver forms an abstraction layer between the JAVA Application and DB, and is implemented by 3rd party vendors or a DB Vendor. But whoever may be the vendor and what ever may be the DB we need not to worry will just us JDCB API to give instructions to JDBC Driver and then its the responsibility of JDBC Driver Provider to convert the JDBC Call to the DB Specific Call. And this 3rd party vendor or DB vendor implemented Drivers are classified into 4-Types namely 1. Type-1 (JDBC ODBC Bridge Driver)

2. Type-2 (Java-Native API Driver) 3. Type-3 (Java Net Protocol Driver) 4. Type-4 (Java Native Protocol driver)
Types Of Drivers Type-1 (JDBC ODBC Bridge Driver) Architecture

JAVA Application

JDBC ODBC Driver

Native ODBC Client driver Libraries

DBMS Interface client libraries

DBMS

DBMS Interface Server Libraries

This type of Driver is designed to convert the JDBC request call to ODBC call and ODBC response call to JDBC call. The JDBC uses this interface in order to communicate with the database, so neither the database nor the middle tier need to be Java compliant. However ODBC binary code must be installed on each client machine that uses this driver. This bridge driver uses a configured data source. Advantages Simple to use because ODBC drivers comes with DB installation/Microsoft front/back office product installation JDBC ODBC Drivers comes with JDK software Disadvantages More number of layers between the application and DB. And more number of API conversions leads to the downfall of the performance. Slower than type-2 driver Where to use? This type of drivers are generaly used at the development time to test your applications. Because of the disadvantages listed above it is not used at production time. But if we are not available with any other type of driver implementations for a DB then we are forced to use this type of driver (for example Microsoft Access). Examples of this type of drivers JdbcOdbcDriver from sun Suns JdbcOdbcDriver is one of type-1 drivers and comes along with sun j2sdk (JDK). Setting environment to use this driver 1. Software ODBC libraries has to be installed. 2. classpath No additional classpath settings are required (c:\j2sdk1.4\jre\lib\rt.jar) which is defaultly configured. 3. Path No additional path configuration is required.

apart

from

the

runtime

jar

How to use this driver 1. Driver class name sun.jdbc.odbc.JdbcOdbcDriver 2. Driver URL jdbc:odbc:<DSN> here <DSN> (Data Source Name) is an ODBC datasource name which is used by ODBC driver to locate one of the ODBC Service Provider implementation API which can in-turn connect to DB. Steps to create <DSN>

1. run Data Sources (ODBC) from Control Panal\Administrative Tools\


(for Windows 2000 server/2000 professional/XP) run ODBC Data Sources from Control Panel\ (for Windows 98)

2. click on Add button available on the above displayed screen.


this opens a new window titled Create New Data Source which displays all the available DBs lable DBs ODBC drivers currently installed on your system.

3. Select the suitable driver and click on Finish


4. Give the required info to the driver (like username, service id etc) Type-2 (Java Native-API Driver) Architecture JDBC Application JDBC API JDBC Type II Driver DBMS Client libraries (native) SP N/W Libra ries DBMS Server libraries (native)

SP API

DBMS

OCI Libraries

This driver converts the JDBC call given by the Java application to a DB specific native call (i.e. to C or C++) using JNI (Java Native Interface). Advantages Faster than the other types of drivers due to native library participation in socket programming Disadvantage DB spcifiic native client library has to be installed in the client machine. Preferablly work in local network environment because network service name must be configured in client system Where to use? This type of drivers are suitable to be used in server side applications. Not recommended to use with the applications using two tire model (i.e. client and database layers) because in this type of model client used to interact with DB using the driver and in such a situation the client system sould have the DB native library. Examples of this type of drivers 1. OCI 8 (Oracle Call Interface) for Oracle implemented by Oracle Corporation. Setting environment to use this driver Software: Oracle client software has to be installed in client machine classpath %ORACLE_HOME%\ora81\jdbc\lib\classes111.zip path %ORACLE_HOME%\ora81\bin How to use this driver Driver class name Driver URL

oracle.jdbc.driver.OracleDriver jdbc:oracle:oci8:@TNSName

Note: TNS Names of Oracle is available in Oracle installed folder %ORACLE_HOME %\Ora81\network\admin\tnsnames.ora 2. Weblogic Jdriver for Oracle implemented by BEA Weblogic: Setting environment to use this driver Oracle client software has to be installed in client machine weblogicoic dlls has to be set in the path classpath d:\bea\weblogic700\server\lib\weblogic.jar path %ORACLE_HOME%\ora81\bin; d:\bea\weblogic700\server\bin\ <sub folder> is

<sub folder>

o oci817_8 if you are using Oracle 8.1.x o oci901_8 for Oracle 9.0.x o oci920_8 for Oracle 9.2.x
How to use this driver Driver class name Driver URL

weblogic.jdbc.oci.Driver jdbc:weblogic:oracle:HostName

Type-3 (Java Net Protocol Driver) Architecture

JDBC Application

JDBC API

JDBC Type III Driver

Net protocol

Middleware Listener

DBMS Interface DBMS


DBMS API

Server Listener

OCI Libraries

DBMS Interface Client

This type of drivers responsibility is to convert JDBC call to Net protocol (Middleware listener dependent) format and redirect the client request to Middleware Listener and middleware listener inturn uses type-1, type-2 or type-4 driver to interact with DB. Advantages:

In absence of DB vendor supplied driver we can use this driver Suitable for Applet clients to connect DB, because it uses Java libraries for communication between client and server.

Disadvantages:

From client to server communication this driver uses Java libraries, but from server to DB connectivity this driver uses native libraries, hence number of API conversion and layer of interactions increases to perform operations that leads to performance deficit.

Third party vendor dependent and this driver may not provide suitable driver for all DBs

Where to use? Suitable for Applets when connecting to databases Examples of this type of drivers: 1. IDS Server (Intersolv) driver available for most of the Databases Setting environment to use this driver Software: IDS software required to be downloaded from the following URL [ http://www.idssoftware.com/idsserver.html -> Export Evaluation ]

classpath path

C:\IDSServer\classes\jdk14drv.jar

How to use this driver Driver class name Driver URL dsn='IDSExamples'

ids.sql.IDSDriver jdbc:ids://localhost:12/conn?

Note: DSN Name must be created in ServerDSN

Type-4 (Java Native Protocol driver) Architecture JDBC Application JDBC API JDBC Type IV Driver DBMS Interface Server Listener
DBMS API

Native Protocol

DBMS This type of driver converts the JDBC call to a DB defined native protocol. Advantage No client native libraries required to be installed in client machine Comes with most of the Databases Disadvantages: Slower in execution compared with other JDBC Driver due to Java libraries are used in socket communication with the DB Where to use? This type of drivers are sutable to be used with server side applications, client side application and Java Applets also. Examples of this type of drivers 1) Thin driver for Oracle implemented by Oracle Corporation Setting environment to use this driver classpath %ORACLE_HOME%\ora81\jdbc\lib\classes111.zip How to use this driver Driver class name oracle.jdbc.driver.OracleDriver Driver URL jdbc:oracle:thin:@HostName:<port no>:<SID>

<port no> 1521 <SID> -> ORCL 2) MySQL Jconnector for MySQL database Setting environment to use this driver classpath C:\mysql\mysql-connector-java-3.0.8-stable\mysqlconnector-java-3.0.8-stable-bin.jar How to use this driver Driver class name com.mysql.jdbc.Driver Driver URL jdbc:mysql:///test Chapter 3 [JDBC Core API] In this chapter we are going to discuss about 3 versions of JDBC: JDBC 1.0, 2.0 and 3.0 Q) How JDBC API is common to all the Databases and also to all drivers? A) Fine! The answer is JDBC API uses Factory Method and Abstract Factory Design pattern implementations to make API common to all the Databases and Drivers. In fact most of the classes available in JDBC API are interfaces, where Driver vendors must provide implementation for the above said interfaces. Q) Then how JDBC developer can remember or find out the syntaxes of vendor specific classes? A) No! developer need not have to find out the syntaxes of vendor specific implementations why because DriverManager is one named class available in JDBC API into which if you register Driver class name, URL, user and password, DriverManager class in-turn brings us one Connection object. Q) Why most of the classes given in JDBC API are interfaces? A) Why abstract class and abstract methods are? Abstract class forces all sub classes to implement common methods whichever are required implementations. Only abstract method and class can do this job. Thats why most part of the JDBC API is a formation of interfaces. JDBC API comes in 2 packages java.sql.* javax.sql.* First of all I want to discuss briefly about all the list of interfaces and classes available in java.sql. package

Interfaces index
Driver

Every JDBC Driver vendor must one sub class of this class for initial establishment of Connections. DriverManager class need to be first registered with this class before accepting URL and other information for getting DB connection. Method index Connection connect(String url, Properties info) This method takes URL argument and user name & password info as Properties object boolean acceptURL(String url) This method returns boolean value true if the given URL is correct, false if any wrong in URL boolean jdbcComplaint() JDBC compliance requires full support for the JDBC API and full support for SQL 92 Entry Level. It is expected that JDBC compliant drivers will be available for all the major commercial databases.

Connection
Connection is class in-turn holds the TCP/IP connection with DB. Functions available in this class are used to manage connection live-ness as long as JDBC application wants to connect with DB. The period for how long the connection exists is called as Session. This class also provides functions to execute various SQL statements on the DB. For instance the operations for DB are mainly divided into 3 types DDL (create, alter, and drop) DML (insert, select, update and delete) DCL (commit, rollback) and also call function_name (or) call procedure_name Method Index Statement createStatement() PreparedStatement prepareStatement(String preSqlOperation) CallableStatement prepareCall(String callToProc())

Statement
Statement class is the super class in its hierarchy. Provides basic functions to execute query (select) and non-related (create, alter, drop, insert, update, delete) query operations. Method Index int executeUpdate(String sql) This function accepts non-query based SQL operations; the return value int tells that how many number of rows effected/updated by the given SQL operation. ResultSet executeQuery(String sql) This function accepts SQL statement SELECT and returns java buffer object which contains temporary instance of SQL structure maintaining all the records retrieved from the DB. This object exists as long as DB connection exist. boolean execute() This function accepts all SQL operations including SELECT statement also.

PreparedStatement

PreparedStatement class is sub classing from Statement class. While connection class prepareStatement function is creating one new instance this class, function takes one String argument that contains basic syntax of SQL operation represented with ? for IN parameter representation. In the further stages of the JDBC program, programmer uses setXXX(int index, datatype identifier) to pass values into IN parameter and requests exdcute()/ exuecteUpdate() call. Method Index setInt(int index, int value) similar functions are provided for all other primitive parameters setString(int index, String value) setObject(int index, Object value) setBinaryStream(int index, InputStream is, int length)

CallableStatement
ResultSet ResultSetMetaData DatabaseMetaData BLOB CLOB REF SavePoint Struct SQLInput SQLOutput SQLData Class diagram required here // TypeIDriverTest,java package com.digitalbook.j2ee.jdbc; import java.sql.*; public class TypeIDriverTest { Connection con; Statement stmt; ResultSet rs; public TypeIDriverTest () { try { // Load driver class into default ClassLoader Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); // Obtain a connection with the loaded driver con =DriverManager.getConnection ("jdbc:odbc:digitalbook","scott","tiger"); // create a statement

st=con.createStatement(); //execute SQL query rs =st.executeQuery ("select ename,sal from emp"); System.out.println ("Name Salary"); System.out.println ("--------------------------------"); while(rs.next()) { System.out.println (rs.getString(1)+" "+rs.getString(2)); } rs.close (); stmt.close (); con.close (); } catch(Exception e) { e.printStackTrace (); } } public static void main (String args[]) { TypeIDriverTest demo=new TypeIDriverTest (); } }

// TypeIIDriverTest,java package com.digitalbook.j2ee.jdbc; import java.sql.*; public class TypeIIDriverTest { Connection con; Statement stmt; ResultSet rs; public TypeIIDriverTest () { try { // Load driver class into default ClassLoader Class.forName ("oracle.jdbc.driver.OracleDriver"); // Obtain a connection with the loaded driver con =DriverManager.getConnection ("jdbc:oracle:oci8:@digital","scott","tiger"); // create a statement st=con.createStatement(); //execute SQL query rs =st.executeQuery ("select ename,sal from emp"); System.out.println ("Name Salary");

System.out.println ("--------------------------------"); while(rs.next()) { System.out.println (rs.getString(1)+" "+rs.getString(2)); } rs.close (); stmt.close (); con.close (); } catch(Exception e) { e.printStackTrace (); } } public static void main (String args[]) { TypeIIDriverTest demo=new TypeIIDriverTest (); } }

Chapter 9 [javax.sql package]


This package supplements the java.sql package and is included as a part of JDK 1.4 version. This package mainly provides following features: 1. DataSource interface was introduced in substitution to DriverManager class for getting connection objects. 2. Connection Pooling 3. Distributed TX management 4. RowSets Applications can directly use DataSource and RowSet API but connection pooling and Distributed TX management APIs are used internally by the middle-tier infrastructure.

DataSource
DataSource is an interface. Driver vendor will provide implementation for this interface (That means in case JDBC Driver Type II driver Oracle vendor for Oracle DB, Intersolv in case of IDSServer). This object is used to obtain connections into any type of JDBC program. Though DriverManager class is ideal for getting DB connection object, this class provides some extra features over DriverManager class: Applications will obtain DB connection objects through via this factory class DataSource object will be registered into JNDI, hence any application connected in the network can obtain this object by requesting JNDI API, DataSource class is having one method called getConnection() geives one Connection object Application do not need to hard code a driver class Changes can be made to a data source properties, which means that it is not necessary to make changes in application code when something about the data source or driver changes Connection pooling and Distributed transactions are available through only the connection obtained from this object. Connection obtained through DriverManager class do not have this capability

DataSource interface is implemented by driver vendor. There are 3 types of implementations available: 1. Basic Implementation- Produces a standard connection object.

2. 3.

Connection Pooling Implementation- Produces a connection object that automatically participates in connection pooling. This implementation works with a middle-tier connection pooling manager. Distributed transaction implementation- Produces a connection object that may be used for distributed transactions and almost always participates in connection pooling. This implementation works with a middle-tier transaction manager and almost always with a connection pool manager.

A driver that is accessed via a DataSource object does not register itself with the DriverManager. Rather, a DataSource object is retrieved though a lookup operation and then used to create a Connection object. With a basic implementation, the connection obtained through a DataSource object is identical to a connection obtained through the DriverManager facility.

Method Index

Connection getConnection() This function returns Connection object on demand of this method. Connection getConnection(String user, String pass) This function returns Connection object on demand of this method by passing username and password.

Sub classes of this interface are Type III Driver IDSServer Intersolv ids.jdbc.IDSDataSource Type III Driver WebLogic BEA weblogic.jdbc.jta.DataSource XA Support

Connection Pooling
Connections made via a DataSource object that is implemented to work with a middle tier connection pool manager will participate in connection pooling. This can improve the performance dramatically because creating a new connection is very expensive. Connection Pool provides following features: Substantial improvement in the performance of DB application can be accomplished by pre-caching the DB connection objects CPM supplied DB connections are remote enable CPM supplied DB connections are cluster aware CPM supplied DB connections supports DTM (distributed TXs) CPM supplied DB connections are not actual DB Connection objects, in turn they are remote object, hence even though client closes DB connection using con.close() the actual connection may not be closed instead RMI connection between client to CPM are closed CPM supplied DB connection objects are serializable, hence client from any where in the network can access DB connections The classes and interfaces used for connection pooling are: ConnectionPoolDataSource PooledConnection ConnectionEvent ConnectionEventListener Connection Pool Manager resided on middle tier system uses these classes and interfaces behind the scenes. When the ConnectionPooledDataSource object is called on to create PooledConnection object, the connection pool manager will register as a ConnectionEventListener object with the new PooledConnection object. When the connection is closed or there is an error, the connection pool manager (being listener) gets a notification that includes a ConnectionEvent object.

Distributed Transactions
As with pooled connections, connections made via data source object that is implemented to work with the middle tier infrastructure may participate in distributed transactions. This gives an application the ability to involve data sources on multiple servers in a single transaction. The classes and interfaces used for distributed transactions are: XADataSource XAConnection These interfaces are used by transaction manager; an application does not use them directly. The XAConnection interface is derived from the PooledConnection interface, so what applies to a pooled connection also applies to a connection that is part of distributed transaction. A transaction manager in the middle tier handles everything transparently. The only change in application code is that an application cannot do anything that would interfere with the transaction managers handling of the transaction. Specifically application cannot call the methods Connection.commit or Connection.rollback and it cannot set the connection to be in auto-commit mode. An application does not need to do anything special to participate in a distributed transaction. It simply creates connections to the data sources it wants to use via the DataSource.getConnection method, just as it normally does. The transaction manager manages the transaction behind the scenes. The XADataSource interface creates XAConnection objects, and each XAConnection object creates an XAResource object that the transaction manager uses to manage the connection.

Rowsets
The RowSet interface works with various other classes and interfaces behind the scenes. These can be grouped into three categories. 1. Event Notification o RowSetListener A RowSet object is a JavaBeansTM component because it has properties and participates in the JavaBeans event notification mechanism. The RowSetListener interface is implemented by a component that wants to be notified about events that occur to a particular RowSet object. Such a component registers itself as a listener with a rowset via the RowSet.addRowSetListener method. When the RowSet object changes one of its rows, changes all of it rows, or moves its cursor, it also notifies each listener that is registered with it. The listener reacts by carrying out its implementation of the notification method called on it. RowSetEvent As part of its internal notification process, a RowSet object creates an instance of RowSetEvent and passes it to the listener. The listener can use this RowSetEvent object to find out which rowset had the event. 2. Metadata o RowSetMetaData This interface, derived from the ResultSetMetaData interface, provides information about the columns in a RowSet object. An application can use RowSetMetaData methods to find out how many columns the rowset contains and what kind of data each column can contain. o

The RowSetMetaData interface provides methods for setting the information about columns, but an application would not normally use these methods. When an application calls the RowSet method execute, the RowSet object will contain a new set of rows, and its RowSetMetaData object will have been internally updated to contain information about the new columns. 3. The Reader/Writer Facility A RowSet object that implements the RowSetInternal interface can call on the RowSetReader object associated with it to populate itself with data. It can also call on the RowSetWriter object associated with it to write any changes to its rows back to the data source from which it originally got the rows. A rowset that remains connected to its data source does not need to use a reader and writer because it can simply operate on the data source directly. o RowSetInternal By implementing the RowSetInternal interface, a RowSet object gets access to its internal state and is able to call on its reader and writer. A rowset keeps track of the values in its current rows and of the values that immediately preceded the current ones, referred to as the original values. A rowset also keeps track of (1) the parameters that have been set for its command and (2) the connection that was passed to it, if any. A rowset uses the RowSetInternal methods behind the scenes to get access to this information. An application does not normally invoke these methods directly. RowSetReader A disconnected RowSet object that has implemented the RowSetInternal interface can call on its reader (the RowSetReader object associated with it) to populate it with data. When an application calls the RowSet.execute method, that method calls on the rowset's reader to do much of the work. Implementations can vary widely, but generally a reader makes a connection to the data source, reads data from the data source and populates the rowset with it, and closes the connection. A reader may also update the RowSetMetaData object for its rowset. The rowset's internal state is also updated, either by the reader or directly by the method RowSet.execute. RowSetWriter A disconnected RowSet object that has implemented the RowSetInternal interface can call on its writer (the RowSetWriter object associated with it) to write changes back to the underlying data source. Implementations may vary widely, but generally, a writer will do the following: Make a connection to the data source Check to see whether there is a conflict, that is, whether a value that has been changed in the rowset has also been changed in the data source Write the new values to the data source if there is no conflict Close the connection

The RowSet interface may be implemented in any number of ways, and anyone may write an implementation. Developers are encouraged to use their imaginations in coming up with new ways to use rowsets. Type III Driver WebLogic BEA weblogic.jdbc.common.internal.ConnectionPool Type III Driver WebLogic BEA weblogic.jdbc.connector.internal.ConnectionPool Type II & IV driver Oracle DB - Oracle -

You might also like