Java Database Connectivity (JDBC) Tutorial

What is JDBC?

JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks commonly associated with database usage:

  • Making a connection to a database
  • Creating SQL or MySQL statements
  • Executing that SQL or MySQL queries in the database
  • Viewing & Modifying the resulting records

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as:

  • Java Applications
  • Java Applets
  • Java Servlets
  • Java ServerPages (JSPs)
  • Enterprise JavaBeans (EJBs)

All of these different executables are able to use a JDBC driver to access a database and take advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.

Pre-Requisite:

Before progressing on this tutorial you need to have good understanding on the following two subjects:

  • o Core JAVA Programming
  • o SQL or MySQL Database
JDBC Architecture:

The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers:

  • 1. JDBC API: This provides the application-to-JDBC Manager connection.
  • 2. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application:

Common JDBC Components:

The JDBC API provides the following interfaces and classes:

  • • DriverManager: This interface manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
  • • Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects
  • • Connection : Interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only.
  • • Statement : You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures.
  • • ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data.
  • • SQLException: This class handles any errors that occur in a database application.

The JDBC 4.0 Packages

The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at the time of writing this tutorial. It offers the main classes for interacting with your data sources.

The new features in these packages include changes in the following areas:

  • • Automatic database driver loading
  • • Exception handling improvements
  • • Enhanced BLOB/CLOB functionality
  • • Connection and statement interface enhancements
  • • National character set support
  • • SQL ROWID access
  • • SQL 2003 XML data type support
  • • Annotations

JDBC - SQL Syntax

Structured Query Language (SQL) is a standardized language that allows you to perform operations on a database, such as creating entries, reading content, updating content, and deleting entries.

SQL is supported by all most any database you will likely use, and it allows you to write database code independently of the underlying database. This tutorial gives an overview of SQL, which is a pre-requisite to understand JDBC concepts. This tutorial gives you enough SQL to be able to Create, Read, Update, and Delete (often referred to as CRUD operations) data from a database.

For a detailed understanding on SQL, you can read our MySQL Tutorial.

Create Database:

The CREATE DATABASE statement is used for creating a new database. The syntax is:

SQL> CREATE DATABASE DATABASE_NAME; Example:

The following SQL statement creates a Database named EMP:

SQL> CREATE DATABASE EMP;

Drop Database:

The DROP DATABASE statement is used for deleting an existing database. The syntax is:

SQL> DROP DATABASE DATABASE_NAME;

Note: To create or drop a database you should have administrator privilege on your database server. Be careful, deleting a database would loss all the data stored in database.

Create Table:

The CREATE TABLE statement is used for creating a new table. The syntax is:
SQL> CREATE TABLE table_name
( column_name column_data_type,
column_name column_data_type,
column_name column_data_type
...
);

JDBC - Environment Setup

To start developing with JDBC setup your JDBC environment by following the steps shown below. We assume that you are working on a Windows platform

Install Java:
Install J2SE Development Kit 5.0 (JDK 5.0)
Make sure following environment variables are set as described below:
  • JAVA_HOME: This environment variable should point to the directory where you installed the JDK, e.g. C:\Program Files\Java\jdk1.5.0
  • CLASSPATH: This environment variable should has appropriate paths set, e.g. C:\Program Files\Java\jdk1.5.0_20\jre\lib
  • PATH: This environment variable should point to appropriate JRE bin, e.g. C:\Program Files\Java\jre1.5.0_20\bin.
  • It is possible you have these variable set already, but just to make sure here's how to check.
  • Go to the control panel and double-click on System. If you are a Windows XP user it's possible you have to open Performance and Maintenance before you will see the System icon.
  • Go to the Advanced tab and click on Environment Variables.
  • Now check all the above mentioned variables are set properly.
You automatically get both JDBC packages java.sql and javax.sql when you install J2SE Development Kit 5.0 (JDK 5.0)

Install Database:

The most important thing you will need, of course is an actual running database with a table that you can query and modify.
Install a database that is most suitable for you. You can have plenty of choices and most common are:

1. MySQL DB: MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8. Accordingly set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation.

2. PostgreSQL DB: PostgreSQL is an open source database. You can download it from PostgreSQL Official Site. The Postgres installation contains a GUI based administrative tool called pgAdmin III. JDBC drivers are also included as part of the installation.

3. Oracle DB: Oracle DB is an commercial database sold by Oracle . We assume that you have the necessary distribution media to install it. Oracle installation includes a GUI based administrative tool called Enterprise Manager. JDBC drivers are also included as part of the installation