Java Database Connectivity
1
JDBC
Definition: JDBC is Java application programming
interface that allows the Java programmers to access
database management system from Java code. It was
developed by JavaSoft, a subsidiary of Sun
Microsystems.
Industry standard for database-independent
connectivity between the Java programming language
and a wide range of databases .
This API lets the programmer connect to a database
and then query and update it , using the SQL.
Product Components of JDBC
The JDBC API.
The JDBC Driver Manager
The JDBC Test Suite.
The JDBC-ODBC Bridge
3
1.The JDBC API
The JDBC API provides the facility for
accessing the relational database from the Java
programming language.
The user not only execute the SQL statements,
retrieve results, and update the data but can also
access it anywhere within a network.
This API has been divided into 2 interfaces
i-) java.sql
ii-) javax.sql.
2. The JDBC Driver Manager
The JDBC Driver Manager is a very important class that
defines objects which connect Java applications to a
JDBC driver.
Driver Manager is the backbone of the JDBC architecture.
It's very simple and small that is used to provide a means
of managing the different types of JDBC database driver
running on an application.
The main responsibility of JDBC database driver is to
load all the drivers found in the system properly as well as
to select the most appropriate driver from opening a
connection to a database
3. The JDBC Test Suite.
The test suite of JDBC application program
interface is very useful for testing a driver
based on JDBC technology during testing
period.
The function of JDBC driver test suite is to
make ensure that the JDBC drivers will run
user's program or not
4. The JDBC-ODBC Bridge
The JDBC-ODBC bridge, also known as JDBC type 1
driver is a database driver that utilize the ODBC driver
to connect the database.
This driver translates JDBC method calls into ODBC
function calls.
The Bridge implements Jdbc for any database for which
an Odbc driver is available.
The Bridge is always implemented as the sun.jdbc.odbc
Java package and it contains a native library used to
access ODBC.
JDBC DRIVERS
Type 1
Type 2
Type 3
Type 4
8
Type 1 JDBC-ODBC Bridge
act as a "bridge" between JDBC
and another database connectivity
mechanism such as ODBC.
The JDBC- ODBC bridge
provides JDBC access using most
standard ODBC drivers.
In this driver the java statements
are converted to a jdbc
statements . JDBC statements
calls the ODBC by using the
JDBC-ODBC Bridge. And finally
the query is executed by the
database
Type 2 Java to Native API.
Type 2 drivers use the Java
Native Interface (JNI) to make
calls to a local database library
API.
This driver converts the JDBC
calls into a database specific call
for databases.
This driver communicates directly
with the database server.
It requires some native code to
connect to the database
Type 3 Java to Network Protocol
Or All- Java Driver.
Type 3 drivers are pure Java drivers that use a
proprietary network protocol to communicate
with JDBC middleware on the server.
The middleware then translates the network
protocol to database-specific function calls.
Type 3 drivers are the most flexible JDBC
solution because they do not require native
database libraries on the client and can
connect to many different databases on the
back end.
Type 3 drivers can be deployed over the
internet without client installation.
Type 4 Java to Database Protocol.
Type 4 drivers are pure Java drivers
that implement a proprietary
database protocol (like Oracle's
SQL*Net) to communicate directly
with the database.
Like Type 3 drivers, they do not
require native database libraries and
can be deployed over the Internet
without client installation.
One drawback to Type 4 drivers is
that they are database specific.
This driver directly converts the java
statements to SQL statements.
Structured Query Language
SQL (Structured Query Language) is a
database sublanguage for querying and
modifying relational databases. It was
developed by IBM Research in the mid 70's
and standardized by ANSI in 1986.
There are 3 basic categories of SQL
Statements:
13
1. SQL-Data Statements -- query and modify tables
and columns
SELECT Statement -- query tables and views in the database
INSERT Statement -- add rows to tables
UPDATE Statement -- modify columns in table rows
DELETE Statement -- remove rows from tables
2. SQL-Transaction Statements -- control transactions
COMMIT Statement -- commit the current transaction
ROLLBACK Statement -- roll back the current transaction
3.SQL-Schema Statements -- maintain
schema (catalog)
CREATE TABLE Statement -- create tables
DROP TABLE Statement -- drop tables
GRANT Statement -- grant privileges on tables and views to
other users
REVOKE Statement -- revoke privileges on tables and views
from other users
Connecting to a Database.
Following steps
– Establish a connection with database
– Send SQL statement
– Process the result
In java we have been provided with some
classes and APIs with which we can make
use of the database as we like
Ex : connect the MySQL database with the Java
file
1. Firstly, we need to establish a connection
between MYSQL and Java files with the help of
MySQL driver.
After establishing a connection we can access or
retrieve data form MySQL database.
.
public class examplejdbc1 {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DATABASE_URL="jdbc:mysql://localhost/books“;
public static void main(String args[]) {
Connection connection=null;
Statement statement=null;
try {
Class.forName(JDBC_DRIVER);
connection=DriverManager.getConnection(DATABASE_URL,"jhtp6","jhtp6");
statement=connection.createStatement();
ResultSet resultset=statement.executeQuery("SELECT * from authors");
ResultSetMetaData metaData=resultset.getMetaData();
int numberOfColumns=metaData.getColumnCount();
while(resultset.next()) {
for(int i=1; i<=numberOfColumns; i++)
System.out.printf(resultset.getObject(i));
System.out.println(); }
} catch(SQLException sqlexception)
{
System.exit(1);
}
18 December 8, 2021 Latika Singh
Connection Interface
This is an interface in java.sql package that specifies connection
with specific database like: MySQL, Ms-Access, Oracle etc and
java files. The SQL statements are executed within the context of the
Connection interface.
Defines methods for interacting with the database via the established
connection
Some methods are
– close()
– getMetaData()
– createStatement()
19
Class.forName(String driver):
This method is static.
It attempts to load the class and returns class
instance and takes string type value (driver)
after that matches class with given string.
DriverManager:
It is a class of java.sql package that controls a set of
JDBC drivers. Each driver has to be register with this
class.
getConnection(String url, String userName, String
password):
This method establishes a connection to specified
database url. It takes three string types of arguments like:
url: - Database url where stored or created your database
userName: - User name of MySQL
password: -Password of MySQL
DatabaseMetaData interface
Provides a vast amount of information about
the database to which a connection is
established
22
example
Import java.sql.*;
Import java.util.*;
class ConnectApp
{
public static void main(String args[]) {
try { Class.forName(com.mysql.jdbc.Driver“);
String url="jdbc:mysql://localhost/books";
Connection
connection=DriverManager.getConnection(url,”root”,”cse8a”);
DatabaseMetaData meta=connection.getMetaData();
System.out.println(“Database :
“+meta.getDatabaseProductName());
System.out.println(“Version : “+meta.getDatabaseProductVersion());
System.out.println(“ User Name :”+meta.getUserName());
connection.close();
}catch(Exception e) { System.out.println(e); System.exit(0); }
23 }
Working with Result Sets
Result of query is returned as a table of data
organized according to rows and columns
Resultset interface provide access to this data
ResultSet object maintains a pointer called
cursor
getMetaData() returns a ResultSetMetaData
object
24
ResultSetMetaData interface
Provides constants and methods that are
used to obtain information about ResultSet
objects
getColumnCount()
getColumnName()
getColumnType()
25
statement interface
Defines methods that are used to interact
with databases via the execution of SQL
statements
Some of the methods are
– executeQuery()
– execute()
– executeUpdate()
26
Transactions
Transaction consists of a group of related
database operations
Database not permanently updated until they
are committed.
If an error has occurred in one of them ,it can
be rolled back as if none of the statements
has been issued.
27
Transaction processing
The setAutoCommit(), commit(), and
rollback() methods of connection interface
are used to implement transaction
processing
28
example
import java.sql.Connection; import java.sql.Statement; import java.sql.DriverManager;
import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException;
public class examplejdbc3
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DATABASE_URL="jdbc:mysql://localhost/books“;
public static void main(String args[]) {
Connection connection=null; Statement statement=null;
try {
Class.forName(JDBC_DRIVER);
connection=DriverManager.getConnection(DATABASE_URL,"jhtp6","jhtp6");
connection.setAutoCommit(false);
statement=connection.createStatement();
Boolean b=statement.execute("INSERT into authors values('9','ninth')");
connection.commit();
}
catch(SQLException sqlexception)
{
sqlexception.printStackTrace();
System.exit(1);
}
}
}
29
Prepared Statements
Java JDBC Prepared statements are pre-
compiled SQL statements. Precompiled SQL is
useful if the same SQL is to be executed
repeatedly.
Inherits from Statement and differs in following
way:
– Have one or more IN parameters (whose value is not
specified when statement is created instead a “?” acts
as a placeholder)
30
Example
PreparedStatement pstmt =
con.prepareStatement( "UPDATE PERSONNEL
SET EMPLOYEE_ID = ? WHERE
EMPLOYEE_NO = 300485");
pstmt.setInt(1, emp);
pstmt.executeUpdate();
31
Types of Result Sets
Different levels of functionality
– Scrollable (cursor moves in both direction)
– Non-scrollable
– Sensitive (changes made reflected in database
tables)
– Insensitive
32
Non Scrollable Result Set.
TYPE_FORWARD_ONLY
– The result set is nonscrollable; its cursor moves
forward only, from the first row to the last row.
33
Scrollable Result Set.
TYPE_SCROLL_INSENSITIVE
The result set is scrollable: Its cursor can move forward or
backward and can be moved to a particular row or to a row
whose position is relative to its current position.
To obtain a scrollable result sets from your queries,you
must obtain a different statement object.
Statement stat=conn.createStatement(type,concurrency);
34
Scrollable Result Set.
TYPE_SCROLL_SENSITIVE
› The result set is scrollable; its cursor can move
forward or backward and can be moved to a
particular row or to a row whose position is relative to
its current position.
› The result set is sensitive to changes made while it is
open. If the underlying column values are modified,
the new values are visible, thus providing a dynamic
view of the underlying data.
35
Concurrency types
The JDBC API offers two update capabilities,
specified by the following constants in the
ResultSet interface:
– CONCUR_READ_ONLY
– CONCUR_UPDATABLE
36
CONCUR_READ_ONLY
› Indicates a result set that cannot be updated programmatically
› Offers the highest level of concurrency (allows the largest
number of simultaneous users). When a ResultSet object with
read-only concurrency needs to set a lock, it uses a read-only
lock. This allow users to read data but not to change it. Because
there is no limit to the number of read-only locks that may be
held on data at one time, there is no limit to the number of
concurrent users unless the DBMS or driver imposes one.
37
CONCUR_UPDATABLE
The result Set can be used to update the
database
write-read lock
38
Example
Connection con =
DriverManager.getConnection( "jdbc:my_subpro
tocol:my_subname");
Statement stmt =
con.createStatement( ResultSet.TYPE_SCROLL
_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
39
Scrollable result sets
resultset.previous( ) //
resultset.relative(n) // n is positive, move cursor
forward, if n is negative, move cursor backward
resultset.absolute(n) // move to nth position
40
Updatable Result Sets (example)
double price = resultset.getDouble(“Price”);
resultset.updateDouble(“Price”,price+increase);
Result.updateRow( );
41