0% found this document useful (0 votes)
22 views

jdbc connectivity notes

jdbc connectivity notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

jdbc connectivity notes

jdbc connectivity notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

 C:\Program Files\NetBeans 8.2\ide\modules\ext\mysql-connector-java-5.1.23-bin.

jar

1.8 INTODUCTION TO JDBC

What is JDBC ?
JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open
Database Connectivity ). JDBC is an standard API specification developed in order to move data
from frontend to backend. This API consists of classes and interfaces written in Java. It basically
acts as an interface (not the one we use in Java) or channel between your Java program and
databases i.e it establishes a link between the two so that a programmer could send data from
Java code and store it in the database for future use.

Why JDBC came into existence ?

JDBC is an advancement for ODBC, ODBC being platform dependent had a lot of drawbacks.
ODBC API was written in C,C++, Python, Core Java and as we know above languages (except
Java and some part of Python )are platform dependent . Therefore to remove dependence, JDBC
was developed by database vendor which consisted of classes and interfaces written in Java.

JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and
SQL Server. JDBC can also be defined as the platform-independent interface between a
relational database and Java programming. It allows java program to execute SQL statement and
retrieve result from database.

We can use JDBC API to handle database using Java program and can perform following
activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

Figure illustrates the core JDBC classes and interfaces that interact with Java and JDBC
applications. This figure also shows the basic relationships of the DatabaseMetaData and
ResultSetMetaData interfaces with other JDBC objects.
Using JDBC database metadata

 DriverManager: This class loads JDBC drivers in memory. It is a “factory” class and can
also be used to create java.sql.Connection objects to data sources(such as Oracle,
MySQL, etc.).
 Connection: This interface represents a connection with a data source. The Connection
object is used for creating Statement, PreparedStatement, and CallableStatement objects.
 DatabaseMetaData: This interface provides detailed information about the database as a
whole. The Connection object is used for creating Database MetaData objects.
 Statement: This interface represents a static SQL statement. It can be used to retrieve
ResultSet objects.
 PreparedStatement: This interface extends Statement and represents a precompiled SQL
statement. It can be used to retrieve ResultSet objects.
 CallableStatement: This interface represents a database stored procedure. It can execute
stored procedures in a database server.
 ResultSet: This interface represents a database result set generated by using SQL’s
SELECT statement. Statement, PreparedStatement, CallableStatement, and other JDBC
objects can create ResultSet objects.
 ResultSetMetaData: This interface provides information about the types and properties of
the columns in a ResultSet object.
 SQLException: This class is an exception class that provides information on a database
access error or other errors.
JDBC 4.0 API
JDBC 4.0 API is mainly divided into two package
1. java.sql
2. javax.sql

java.sql package

This package include classes and interface to perform almost all JDBC operation such as creating
and executing SQL Queries.

Important classes and interface of java.sql package


classes/interface Description

java.sql.BLOB Provide support for BLOB(Binary Large Object) SQL type.

java.sql.Connection creates a connection with specific database

java.sql.CallableStatement Execute stored procedures

java.sql.CLOB Provide support for CLOB(Character Large Object) SQL type.

java.sql.Date Provide support for Date SQL type.

java.sql.Driver create an instance of a driver with the DriverManager.

java.sql.DriverManager This class manages database drivers.

java.sql.PreparedStatement Used to create and execute parameterized query.

It is an interface that provide methods to access the result row-by-


java.sql.ResultSet
row.

java.sql.Savepoint Specify savepoint in transaction.

java.sql.SQLException Encapsulate all JDBC related exception.

java.sql.Statement This interface is used to execute SQL statements.

javax.sql package

This package is also known as JDBC extension API. It provides classes and interface to access
server-side data.

Important classes and interface of javax.sql package


classes/interface Description
javax.sql.ConnectionEvent Provide information about occurrence of event.

Used to register event generated by PooledConnection


javax.sql.ConnectionEventListener
object.

javax.sql.DataSource Represent the DataSource interface used in an application.

javax.sql.PooledConnection provide object to manage connection pools.

1.9 JDBC DRIVERS:

JDBC Driver is required to process SQL requests and generate result. The following are the
different types of driver available in JDBC.

 Type-1 Driver or JDBC-ODBC bridge


 Type-2 Driver or Native API Partly Java Driver
 Type-3 Driver or Network Protocol Driver
 Type-4 Driver or Thin Driver

JDBC-ODBC bridge

Type-1 Driver act as a bridge between JDBC and other database connectivity
mechanism(ODBC). The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. This is now discouraged because of thin driver.

In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantage

 Easy to use
 Allow easy connectivity to all database supported by the ODBC Driver.

Disadvantage

 Slow execution time


 Dependent on ODBC Driver.
 Uses Java Native Interface(JNI) to make ODBC call.

Native API Driver

This type of driver make use of Java Native Interface(JNI) call on database specific native client
API. These native client API are usually written in C and C++.

The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.
Advantage

 faster as compared to Type-1 Driver


 Contains additional features.

Disadvantage

 The Native driver needs to be installed on the each client machine.


 The Vendor client library needs to be installed on client machine.
 Increased cost of Application

Network Protocol Driver

This driver translate the JDBC calls into a database server independent and Middleware server-
specific calls. Middleware server further translate JDBC calls into database specific calls.

The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage

 Does not require any native library to be installed because of application server that can
perform many tasks like auditing, load balancing, logging etc.
 Database Independency.
 Provide facility to switch over from one database to another database.

Disadvantage

 Slow due to increase number of network call.


 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier

Thin Driver

This is Driver called Pure Java Driver because. This driver interact directly with database. It does
not require any native database library. The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is known as thin driver. It is fully written in

Java language.

Advantage

 Does not require any native library.


 Does not require any Middleware server.
 Better Performance than other driver.

Disadvantage

 Slow due to increase number of network call.


 Drivers depend on the Database.

Which Driver should be Used?

If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.

1.10 ARCHITECTURES:
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 −

1.10.1Common JDBC Components


JDBC includes four components:

1. The JDBC API — The JDBC™ API provides programmatic access to relational data
from the Java™ programming language. Using the JDBC API, applications can execute
SQL statements, retrieve results, and propagate changes back to an underlying data
source. The JDBC API can also interact with multiple data sources in a distributed,
heterogeneous environment.

The JDBC API is part of the Java platform, which includes the Java™ Standard Edition
(Java™ SE ) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is
divided into two packages: java.sql and javax.sql. Both packages are included in the
Java SE and Java EE platforms.

2. JDBC Driver Manager — The JDBC DriverManager class defines objects which can
connect Java applications to a JDBC driver. DriverManager has traditionally been the
backbone of the JDBC architecture. It is quite small and simple.

The Standard Extension packages javax.naming and javax.sql let you use a
DataSource object registered with a Java Naming and Directory Interface™ (JNDI)
naming service to establish a connection with a data source. You can use either
connecting mechanism, but using a DataSource object is recommended whenever
possible.
3. JDBC Test Suite — The JDBC driver test suite helps you to determine that JDBC
drivers will run your program. These tests are not comprehensive or exhaustive, but they
do exercise many of the important features in the JDBC API.
4. JDBC-ODBC Bridge — The Java Software bridge provides JDBC access via ODBC
drivers. Note that you need to load ODBC binary code onto each client machine that uses
this driver. As a result, the ODBC driver is most appropriate on a corporate network
where client installations are not a major problem, or for application server code written
in Java in a three-tier architecture.

This Trail uses the first two of these these four JDBC components to connect to a database and
then build a java program that uses SQL commands to communicate with a test Relational
Database. The last two components are used in specialized environments to test web
applications, or to communicate with ODBC-aware DBMSs.

Two-tier and Three-tier Processing Models:

The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.

In the two-tier model, a Java applet or application talks directly to the data source. This requires
a JDBC driver that can communicate with the particular data source being accessed. A user's
commands are delivered to the database or other data source, and the results of those statements
are sent back to the user. The data source may be located on another machine to which the user is
connected via a network. This is referred to as a client/server configuration, with the user's
machine as the client, and the machine housing the data source as the server. The network can be
an intranet, which, for example, connects employees within a corporation, or it can be the
Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the
commands to the data source. The data source processes the commands and sends the results
back to the middle tier, which then sends them to the user. MIS directors find the three-tier
model very attractive because the middle tier makes it possible to maintain control over access
and the kinds of updates that can be made to corporate data. Another advantage is that it
simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can
provide performance advantages.

Figure 2: Three-tier Architecture for Data Access.


Until recently, the middle tier has often been written in languages such as C or C++, which offer
fast performance. However, with the introduction of optimizing compilers that translate Java
bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans™,
the Java platform is fast becoming the standard platform for middle-tier development. This is a
big plus, making it possible to take advantage of Java's robustness, multithreading, and security
features.

With enterprises increasingly using the Java programming language for writing server code, the
JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of
the features that make JDBC a server technology are its support for connection pooling,
distributed transactions, and disconnected rowsets. The JDBC API is also what allows access to a
data source from a Java middle tier.

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.
1.11 CURD OPERATION USING JDBC:

CRUD - Create, Retrieve, Update and:. These CRUD operations are equivalent to the INSERT,
SELECT, UPDATE and DELETE statements in SQL language.

JDBC CRUD ( Create, Read, Update and Delete) example

Step 1: Establish connection with database


Step 2: Create following table in MySQL database server -

use test;
create table Emp
(
code varchar(10) primary key,
name varchar(40) null,
city varchar(20),
salary int
);
insert into Emp values('a001','Ram Kumar','Noida',10000);

Step3 : Following code to insert record in the above table -

public void insertEmp(String code, String name, String city, int sal) {
try {
ps = con.prepareStatement("insert into Emp values(?,?,?,?)");
ps.setString(1, code);
ps.setString(2, name);
ps.setString(3, city);
ps.setInt(4, sal);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println("Inserted");
} else {
System.out.println("not Inserted");
}
} catch (Exception e) {
e.printStackTrace();
}
}

Step4 : Following source code is to update employee city and salary based on employee code -

public void updateEmp(String code, String city, int salary) {


try {
ps = con.prepareStatement("update emp set city=?,salary=salary+? where cod
e=?");
ps.setString(1, city);
ps.setInt(2, salary);
ps.setString(3, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println("updated");
} else {
System.out.println("not updated");
}
} catch (Exception e) {
e.printStackTrace();
}
}

Step5 : Following source code is to delete an employee record based on employee code -

public void deleteEmp(String code) {


try {
ps = con.prepareStatement("delete from emp where code=?");
ps.setString(1, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println("deleted");
} else {
System.out.println("not deleted");
}
} catch (Exception e) {
e.printStackTrace();
}
}

Step6 : Following source code is to display an employee record based on employee code -

public void dispAnEmp(String s) {


try {
ps = con.prepareStatement("select * from Emp where code=?");
ps.setString(1, s);
ResultSet res = ps.executeQuery();
if (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}

Step7 : Following source code is to display whole records from employee table -

public void dispAll() {


try {
Statement st = con.createStatement();
ResultSet res = st.executeQuery("select * from emp");
while (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}

package jdbc;

import java.sql.*;
import java.io.*;

public class CRUD {

Connection con;
PreparedStatement ps;

public CRUD() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test?
user=root&password=root");
} catch (Exception e) {
e.printStackTrace();
}
}

public void insertEmp(String code, String name, String city, int sal) {
try {
ps = con.prepareStatement("insert into Emp values(?,?,?,?)");
ps.setString(1, code);
ps.setString(2, name);
ps.setString(3, city);
ps.setInt(4, sal);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println("Inserted");
} else {
System.out.println("not Inserted");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void updateEmp(String code, String city, int salary) {


try {
ps = con.prepareStatement("update emp set city=?,salary=salary+? where code=?");
ps.setString(1, city);
ps.setInt(2, salary);
ps.setString(3, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println("updated");
} else {
System.out.println("not updated");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void deleteEmp(String code) {


try {
ps = con.prepareStatement("delete from emp where code=?");
ps.setString(1, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println("deleted");
} else {
System.out.println("not deleted");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void dispAll() {


try {
Statement st = con.createStatement();
ResultSet res = st.executeQuery("select * from emp");
while (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public void dispAnEmp(String s) {


try {
ps = con.prepareStatement("select * from Emp where code=?");
ps.setString(1, s);
ResultSet res = ps.executeQuery();
if (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


try {
CRUD obj = new CRUD();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int ch = 0;
while (true) {
System.out.println("Employee management \n"
+ "1. Add Employee \n "
+ "2. Edit Employee \n "
+ "3. Delete Employee \n "
+ "4. Display all record \n "
+ "5. Display a record \n"
+ "6. Exit"
+ "Enter option \n");
String str1 = br.readLine().toString();
ch = Integer.parseInt(str1);
switch (ch) {
case 1: {
System.out.println("Enter Employee Code");
String code = br.readLine();
System.out.println("Enter Employee Name");
String name = br.readLine();
System.out.println("Enter Employee City");
String city = br.readLine();
System.out.println("Enter Employee Salary");
String sal = br.readLine();
int salary = Integer.parseInt(sal);
obj.insertEmp(code, name, city, salary);
break;
}
case 2: {
System.out.println("Enter Employee Code");
String code = br.readLine();
System.out.println("Enter Employee City");
String city = br.readLine();
System.out.println("Enter Employee Salary");
String sal = br.readLine();
int salary = Integer.parseInt(sal);
obj.updateEmp(code, city, salary);
break;
}
case 3: {
System.out.println("Enter Employee Code to delete record");
String code = br.readLine();
obj.deleteEmp(code);
break;
}
case 4: {
obj.dispAll();
break;
}
case 5: {
System.out.println("Enter Employee Code to display record");
String code = br.readLine();
obj.dispAnEmp(code);
break;
}
case 6:
{
System.exit(0);
}
default:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

1.12 CONNECTING TO NON CONVENTIONAL DATABASE:

Steps for connectivity between Java program and database

1. Loading the Driver


To begin with, you first need load the driver or register it before using it in the program .
Registration is to be done once in your program. You can register a driver in one of two ways
mentioned below :

 Class.forName() : Here we load the driver’s class file into memory at the runtime. No
need of using new or creation of object .The following example uses Class.forName() to
load the Oracle driver –

Class.forName(“oracle.jdbc.driver.OracleDriver”);

 DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static


member register. Here we call the constructor of the driver class at compile time . The
following example uses DriverManager.registerDriver()to register the Oracle driver –

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())

2. Create the connections


After loading the driver, establish connections using :

Connection con = DriverManager.getConnection(url,user,password)

user – username from which your sql command prompt can be accessed.
password – password from which your sql command prompt can be accessed.

con: is a reference to Connection interface.


url : Uniform Resource Locator. It can be created as follows:

String url = “ jdbc:oracle:thin:@localhost:1521:xe”

Where oracle is the database used, thin is the driver used , @localhost is the IP Address where
database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above
are of String type and are to be declared by programmer before calling the function. Use of this
can be referred from final code.

3. Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to send
SQL commands and receive data from your database.
Use of JDBC Statement is as follows:

Statement st = con.createStatement();

Here, con is a reference to Connection interface used in previous step .

4. Execute the query


Now comes the most important part i.e executing the query. Query here is an SQL Query . Now
we know we can have multiple types of queries. Some of them are as follows:

 Query for updating / inserting table in a database.


 Query for retrieving data .

The executeQuery() method of Statement interface is used to execute queries of retrieving values
from the database. This method returns the object of ResultSet that can be used to get all the
records of a table.
The executeUpdate(sql query) method ofStatement interface is used to execute queries of
updating/inserting .

Example:

int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");

Here sql is sql query of the type String

5.Close the connections


So finally we have sent the data to the specified location and now we are at the verge of
completion of our task .
By closing connection, objects of Statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
Example :

con.close();
Applications of JDBC

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy