OOPJ Unit 5 Material - Part 2
OOPJ Unit 5 Material - Part 2
- Introduction
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 mentioned below that are commonly associated with database
usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing 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 moving further, you need to have a good understanding of the following two subjects −
Core JAVA Programming
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 −
JDBC API − This provides the application-to-JDBC Manager connection.
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 class manages a list of database drivers. Matches connection requests from the java
application with the proper database driver using communication sub protocol. 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 − This 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 - Environment Setup
To start developing with JDBC, you should setup your JDBC environment by following the steps shown below. We
assume that you are working on a Windows platform.
Install Java
Java SE is available for download for free. To download click here, please download a version compatible with your
operating system.
Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed
Java on your machine, you would need to set environment variables to point to correct installation directories.
Setting Up the Path for Windows 2000/XP
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example,
if the path is currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin
Setting Up the Path for Windows 95/98/ME
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH = %PATH%;C:\Program Files\java\jdk\bin
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your
shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −
export PATH = /path/to/java:$PATH'
You automatically get both JDBC packages java.sql and javax.sql, when you install J2SE Development Kit.
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 −
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.
Set Database Credential
When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your
choice.
Using root ID and password you can either create another user ID and password, or you can use root ID and
password for your JDBC application.
There are various database operations like database creation and deletion, which would need administrator ID
and password.
For rest of the JDBC tutorial, we would use MySQL Database with guest as ID and guest123 as password.
If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to
create a user ID and password for you.
Create Database
To create the TUTORIALSPOINT database, use the following steps −
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also
check documentation on how to start and stop your database server.
Step 2
Start the database server by executing the following command, if it is already not running.
C:\Program Files\MySQL\bin>mysqld
C:\Program Files\MySQL\bin>
Step 3
Create the TUTORIALSPOINT database by executing the following command −
C:\Program Files\MySQL\bin> mysqladmin create TUTORIALSPOINT -u guest -p
Enter password: ********
C:\Program Files\MySQL\bin>
Create Table
To create the Employees table in TUTORIALSPOINT database, use the following steps −
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u guest -p
Enter password: ********
mysql>
Step 3
Create the table Employees as follows −
mysql> use TUTORIALSPOINT;
mysql> create table Employees
-> (
-> id int not null,
-> age int not null,
-> first varchar (255),
-> last varchar (255)
-> );
Query OK, 0 rows affected (0.08 sec)
mysql>
Create Data Records
Finally you create few records in Employee table as follows −
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)
mysql>
ODBC Driver needs Database Name & its Location to connect with Database. ODBC Driver collect this Information
from DSN i.e. internally ODBC Driver will use DSN to get Database Information (DSN Concept applicable only for
Type-1 Driver). There are 3 Types of DSN
1. User DSN
It is the non-sharable DSN and available only for Current User.
2. System DSN
It is the sharable DSN and it is available for all Users who can access that System. It is also known as Global DSN.
3. File DSN
It is exactly same as User DSN but will be stored in a File with .dsn Extension.
Program To Establish Connection To The Oracle Database By Using Type-1 Driver?
import java.sql.*;
/**
*
* @author ashok.mariyala
*
*/
public class DbConnectDemo {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:demodsn","scott","tiger");
if(con != null) {
System.out.println("Connection established Successfully");
} else {
System.out.println("Connection not established");
}
}
}
In the above Program Class.forName() is Optional, because from JDBC] 4.0V/ Java 1.6V on wards Driver Class will
be loaded automatically from the Class Path based on “jdbcurl”.
To Compile and Run above Program we are not required to Place/Set any Jar File in the Class Path, because Type-1
Driver is available by default as the Part of JDK.
Connection is an interface, then how we can get Connection Object?
We are not getting Connection Object and we are getting its Implementation Class Object. This Implementation
Class is available as the Part of Driver Software. Driver Software Vendor is responsible to provide Implementation
Class. We can print corresponding Class Name as follows
System.out.println(conn.getClass().getName());
Output
sun.jdbc.odbc.JdbcOdbcConnection
Advantage Of Using Interface Names In Our Application Instead Of Using Implementation Class Names
Interface Reference can be used to hold implemented Class Object. This Property is called Polymorphism.
Connection ➔ sun.jdbc.odbc.JdbcOdbcConnection ➔ Type-1
Connection ➔ orcale.jdbc.OracleT4Connection ➔ Type-2
In JDBC Programs, Interface Names are fixed and these are provided by JDBC API. But Implementation Classes are
provided by Driver Software Vendor and these Names are varied from Vendor to Vendor. If we Hard Code Vendor
provided Class Names in our Program then the Program will become Driver Software Dependent and won’t work
for other Drivers.
If we want to change Driver Software then Total Program has to rewrite once again, which is difficult. Hence it is
always recommended to use JDBC API provided Interface Names in our Application.
3. Creation of Statement Object
Once we established Connection between Java Application and Database, we have to prepare SQL Query and we
have to send that Query to the Database. Database Engine will execute that Query and send Result to Java
Application.
To send SQL Query to the Database and to bring Results from Database to Java Application some Vehicle must be
required, which is nothing but Statement Object. We can create Statement Object by
using createStatement() Method of Connection Interface.
Example
Statement st = con.createStatement();
4: Prepare, Send and Execute SQL Query
According to Database Specification, all SQL Commands are divided into following Types
1. DDL (Data Definition Language) Commands
E.g: Create Table, Alter Table, Drop Table Etc
2. DML (Data Manipulation Language) Commands
E.g: Insert, Delete, Update
3. DQL (Data Query Language) Commands
E.g: Select
4. DCL (Data Control Language) Commands
E.g: Alter Password, Grant Access Etc..
5. Data Administration Commands
E.g: Start Audit
Stop Audit
6. Transactional Control Commands
Commit, Rollback, Savepoint Etc
According to Java Developer Point of View, all SQL Operations are divided into 2 Types.
1. Select Operations (DQL)
2. Non-Select Operations (DML, DDL Etc)
Once we create Statement Object, we can call the following Methods on that Object to execute our Queries.
1. executeQuery()
2. executeUpdate()
3. execute()
1. executeQuery() Method
We can use this Method for Select Operations. Because of this Method Execution, we will get a Group of Records,
which are represented by ResultSet Object. Hence the Return Type of this Method is ResultSet.
E.g:
ResultSet rs = st.executeQuery("select * from emp");
2. executeUpdate() Method
We can use this Method for Non-Select Operations (Insert|Delete|Update). Because of this Method Execution, we
won’t get a Group of Records and we will get a Numeric Value represents the Number of Rows effected. Hence
Return Type of this Method is int.
E.g
int rowCount = st.executeUpdate("delete from emp where sal<15000");
3. execute() method
We can use this Method for both Select and Non-Select Operations. If we don’t know the Type of Query at the
beginning and it is available dynamically at run time then we should use this execute() Method.
E.g
boolean b = st.execute("dynamically provided query");
if(b==true)//select query {
ResultSet rs=st.getResultSet(); //use rs to get data
} 8) else// non-select query {
int rowCount=st.getUpdateCount();
}
executeQuery() Vs executeUpdate() Vs execute()
If we know the Type of Query at the beginning and it is always Select Query then we should use
“executeQuery() Method”.
If we know the Type of Query at the beginning and it is always Non-Select Query then we should use
executeUpdate() Method.
If we don’t know the Type of SQL Query at the beginning and it is available dynamically at Runtime (May be
from Properties File OR From Command Prompt Etc) then we should go for execute() Method.
Note
Based on our Requirement we have to use corresponding appropriate Method.
st.executeQuery();
st.executeUpdate();
st.execute();
st.getResultSet();
st.getUpdateCount();
Case 1 : executeQuery() Vs Non-Select Query
Usually we can use executeQuery() Method for Select Queries. If we use for Non-Select Queries then we cannot
expect exact Result. It is varied from Driver to Driver.
E.g
ResultSet rs = st.executeQuery("delete from emp where sal<15000");
For Type-1 Driver we will get SQLException. But for Type-4 Driver we won’t get any Exception and Empty ResultSet
will be returned.
Case 2: executeUpdate() Vs Select Query
Usually we can use executeUpdate() Method for Non-Select Queries. But if we use for Select Queries then we
cannot expect the Result and it is varied from Driver to Driver.
E.g
int rowCount = st.executeUpdate("select * from emp");
For Type-1 Driver we will get SQLException where as for Type-4 Driver we won’t get any Exception and simply
returns the Number of Rows selected.
Case 3: executeUpdate() Vs DDL Queries
If we use executeUpdate() Method for DDL Queries like Create Table, Alter Table, Drop Table Etc, then Updated
Record Count is not applicable. The Result is varied from Driver to Driver.
E.g
System.out.println(rs.getInt("eno")+".."+rs.getString("ename")+".."+rs.getDouble("sal")+".."+rs.getString("Addr"));
OR
System.out.println(rs.getInt(1)+".."+rs.getString(2)+".."+rs.getDouble(3)+".."+rs.getString(4));
}
Readability wise it is recommended to use Column Names, but Performance wise it is recommended to use
Column Index. (Because comparing Numbers is very easy than comparing String Values). Hence if we are handling
very large Number of Records then it is highly recommended to use Index.
If we know Column Name then we can find corresponding Index as follows.
int columnIndex = rs.findColumn(String columnName);
Conclusions
1. ResultSet follows “Iterator” Design Pattern.
2. ResultSet Object is always associated with Statement Object.
3. Per Statement only one ResultSet is possible at a time. if we are trying to open another ResultSet then
automatically first ResultSet will be closed.
E.g
Statement st = con.createStatement();
ResultSet rs1 = st.executeQuery("select * from emp");
ResultSet rs2 = st.executeQuery("select * from student");
In the above Example rs1 will be closed automatically whenever we are trying to open rs2.
6. Close the Connection
After completing Database Operations it is highly recommended to close the Resources whatever we opened in
reverse order of opening.
1.rs.close();
It closes the ResultSet and won’t allow further processing of ResultSet
2. st.close();
It closes the Statement and won’t allow sending further Queries to the Database.
3. conn.close();
It closes the Connection and won’t allow for further Communication with the Database.
Conclusions
Per Statement only one ResultSet is possible at a time.
Per Connection multiple Statement Objects are possible.
Whenever we are closing Statement Object then automatically the corresponding ResultSet will be closed.
Similarly, whenever we are closing Connection Object automatically corresponding Statement Objects will
be closed.
Hence we required to use only con.close();