1659628883_JDBCXML
1659628883_JDBCXML
2.JDBC Drivers
To connect with individual databases, JDBC requires drivers for each database.
The various driver types are described in the following sections:
Type I: JDBC-ODBC Bridge
Type II: Native API/JAVA
Type III: Pure Java driver for database middleware(JDBC protocol)
Type Four Driver : Direct-to-database pure Java driver (JAVA protocol)
Type 1: JDBC-ODBC Bridge Driver
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN)
that represents the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or
when no other alternative is available.
5.Database connection:
The setXXX() methods bind values to the parameters, where XXX represents the Java
data type of the value you wish to bind to the input parameter.
o setXXX(int,string);
First parameter represent the column index and second parameter represent the values
that replace the ? mark in the query.
Next different execut methods of the preparedStatement object are called.
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
PreparedStatement p=c.PreaparedStatement(“select name from emp where usn=?”);
p.setSting(2, ”12cs001”);
ResultSet r=p.executeQuery();
Program:
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
CallableStatement p=c.CallableSatement(“Call lastOrderNumber(?)”);
p.registerOutParameter(1,TYPES.VARCHAR);
p.executeQuery();
6. ResultSet
A ResultSet consists of records. Each records contains a set of columns.
A ResultSet can be of a certain type. The type determines some characteristics and abilities of the
ResultSet.
Scrollable ResultSet:
At the time of writing there are three ResultSet types:
1. ResultSet.TYPE_FORWARD_ONLY
2. ResultSet.TYPE_SCROLL_INSENSITIVE
3. ResultSet.TYPE_SCROLL_SENSITIVE
The default type is TYPE_FORWARD_ONLY
TYPE_FORWARD_ONLY means that the ResultSet can only be navigated forward. That is,
you can only move from row 1, to row 2, to row 3 etc. You cannot move backwards in
the ResultSet.
TYPE_SCROLL_INSENSITIVE means that the ResultSet can be navigated (scrolled) both
forward and backwards. You can also jump to a position relative to the current position,
Method Description
absolute() Moves the ResultSet to point at an absolute position. The position is a row
number passed as parameter to the absolute() method.
afterLast() Moves the ResultSet to point after the last row in the ResultSet.
beforeFirst() Moves the ResultSet to point before the first row in the ResultSet.
first() Moves the ResultSet to point at the first row in the ResultSet.
last() Moves the ResultSet to point at the last row in the ResultSet.
next() Moves the ResultSet to point at the next row in the ResultSet.
previous() Moves the ResultSet to point at the previous row in the ResultSet.
relative() Moves the ResultSet to point to a position relative to its current position. The
relative position is passed as a parameter to the relative method, and can be
both positive and negative.
PROGRAM:
import java.sql.*;
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
releaseSavePoint(String);-it realse the save point assing to the sql statement if and only
rollback();-if one of the sql statement is failed,then rollback() method is invoked and
control goes back to the fail sql statement for further execution.
Program:
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
8.Metadata:
Metadata is data about data. J2ee component can access metadata by using
DatabaseMetaData interface.
ResultSetMetaData interface
DatabaseMetaData interface:
The DatabaseMetaData interface is used to retrieve information about database,table,columns
and index amoung other information about dbms.
ResultSetMetaData interface:
ResultSetMetaData interface is used to retrieve the information by calling the getMetaData()
method of ResultSet interface.
Different methods in the ResultSetMetaData inetface are as follows:
getColunmCount()-returns the number of column available in the table
getColunmName(int)-returns the name of column specified by the column
number
getColunmTye(int)-returns the type of column specified by the column number
program:
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
Statement s=c.createStatement();
ResultSet r=s.executeQuery(“Select *from emp”);
ResultSetMetaData d=r.getMetaData();
System.out.println(d.getColunmName(1));
Data Types:
The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the
database. It uses a default mapping for most data types. The following table summarizes the default
JDBC data type that the Java data type is converted to, when you call the setXXX() method.
SQL JDBC/Java
VARCHAR String
CHAR String
LONGVARCHAR String
BIT boolean
NUMERIC java.math.BigDecimal
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT float
DOUBLE double
Exception :
SQLException Methods
An SQLException can occur both in the driver and the database. When such an exception occurs,
an object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving additional
information about the exception −
Method Description
getErrorCode( ) Gets the error number associated with the exception.
Gets the JDBC driver's error message for an error,
getMessage( ) handled by the driver or gets the Oracle error number
and message for a database error.
Gets the XOPEN SQLstate string. For a JDBC driver
error, no useful information is returned from this
getSQLState( )
method. For a database error, the five-digit XOPEN
SQLstate code is returned. This method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
Prints the current exception, or throwable, and it's
printStackTrace( )
backtrace to a standard error stream.
Prints this throwable and its backtrace to the print
printStackTrace(PrintStream s)
stream you specify.
Prints this throwable and it's backtrace to the print
printStackTrace(PrintWriter w)
writer you specify.
DatabaseMetaData in Java, which resides in java.sql package, provides information about the
database (DB meta data) you are connected to.
Using the methods provided by Java DatabaseMetaData interface you can get information
about-
In this post we’ll see examples of some of the commonly used methods. You can get the list
of full methods here-
https://docs.oracle.com/javase/9/docs/api/java/sql/DatabaseMetaData.html
Table of contents
You can get the DatabaseMetaData instance by calling the getMetaData() method of the
Connection class.
This example code shows how you can get DB name and version information using
DatabaseMetaData in JDBC.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
// Creating connection
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs",
"root", "admin");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(connection != null){
//closing connection
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // if condition
}// finally
}
}
// Creating connection
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs",
"root", "admin");
For getting tables you can use getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types) method. You can provide null as value for all the
parameters, that way you don’t narrow the search and all the tables are returned. If you want
to narrow your search to get specific tables then you can provide values for these parameters.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
// Creating connection
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/world",
"root", "admin");
Output
Here I am connecting to “world” schema in MySQL and getting all the tables.
Each table description in the returned ResultSet has the following columns:
That’s why column index is 3 while getting result from ResultSet as TABLE_NAME is at
number 3.
For getting procedures you can use getProcedures(String catalog, String schemaPattern,
String procedureNamePattern) method. Again you can pass null as value for all the
parameters if you don’t want to narrow the search.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
// Creating connection
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs",
"root", "admin");
while (rs.next()){
System.out.println("Procedure name " + rs.getString(3));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(connection != null){
//closing connection
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // if condition
}// finally
}
}
Each procedure description in the returned ResultSet has the following columns:
The Tutorial helps you to know understand an example from JDBC Metadata Get table. In
this program, the code describe you JDBC Meta Data Get tables that explain the column
property and structure of table. The class Jdbc MetaDataGettables include the list of methods
to get the meta data property of table as given follow -
executeQuery ( ) -The method retrieve a record set from a table in database. The retrieve
record set is assigned to a result set.
getMetaData ( ) - The Result Set call get Metadata( ),which return you the property of the
retrieve record set (length,field,column).Meta Data account for data element and its attribute.
getcolumncount ( ) -The method return you a integer data type and provides you the
number of column in the Result set object.
Finally the println print the table name, field, size and data type.
In case there is an exception in the try block The subsequent catch block caught and handle
the exception.
JdbcMetaDataGettables.java
import java.sql.*;
try {
Class.forName(driver);
Connection con =
DriverManager.getConnection(connection, user, password);
Statement st = con.createStatement();
} catch (Exception e) {
System.out.println(e);
}
}
}
What Is CallableStatement In Java?
CallableStatement is an interface in JDBC API which is used to call the stored procedures
from the Java code. CallableStatement extends PreparedStatement which in turn extends
Statement. Below image shows the template to how to get CallableStatement object, how to
set IN parameters, how to register OUT parameters and how to retrieve the result returned by
the stored procedure.
Now, let’s see some examples on how to call stored procedures with IN, OUT and IN OUT
parameters.
Java Program :
1 import java.sql.*;
2
3 public class CallableStatementExample
{
4 static
5 {
6 //STEP 1 : Registering The Driver Class
7
8 try
{
9 Class.forName("oracle.jdbc.driver.OracleDriver");
10 }
11 catch (ClassNotFoundException e)
12 {
13 System.out.println("Unable To Load The Driver class");
}
14 }
15
16 public static void main(String[] args)
17 {
18 Connection con = null;
19
20 CallableStatement cstmt = null;
21
try
22 {
23 //Database Credentials
24
25 String URL = "jdbc:oracle:thin:@localhost:1521:XE";
26
27 String username = "username";
28
29 String password = "password";
30
//STEP 2 : Creating The Connection Object
31
32
con = DriverManager.getConnection(URL, username, password);
33
34 //STEP 3 : Creating The CallableStatement Object
35
36 cstmt = con.prepareCall("{call P1}");
37
38 //STEP 4 : Executing The CallableStatement
39
40 cstmt.execute();
41 }
catch (SQLException e)
42 {
43 e.printStackTrace();
44 }
45 finally
{
46 //STEP 5 : Closing The DB Resources
47
48 //Closing the CallableStatement object
49
50 try
51 {
52 if(cstmt!=null)
{
53 cstmt.close();
54 cstmt=null;
55 }
56 }
57 catch (SQLException e)
{
58 e.printStackTrace();
}
59
60
//Closing the Connection object
61
62 try
63 {
64 if(con!=null)
65 {
con.close();
66 con=null;
67 }
68 }
69 catch (SQLException e)
70 {
e.printStackTrace();
71 }
72 }
73 }
74}
75
76
77
78
79
80
81
82
83
84
85
86
Java Program :
1 import java.sql.*;
2
3 public class CallableStatementExample
{
4 static
5 {
6 //STEP 1 : Registering The Driver Class
7
8 try
9 {
Class.forName("oracle.jdbc.driver.OracleDriver");
10 }
11 catch (ClassNotFoundException e)
12 {
13 System.out.println("Unable To Load The Driver class");
}
14 }
15
16 public static void main(String[] args)
17 {
18 Connection con = null;
19
20 CallableStatement cstmt = null;
21
try
22 {
23 //Database Credentials
24
25 String URL = "jdbc:oracle:thin:@localhost:1521:XE";
26
27 String username = "username";
28
29 String password = "password";
30
//STEP 2 : Creating The Connection Object
31
32
con = DriverManager.getConnection(URL, username, password);
33
34 //STEP 3 : Creating the CallableStatement object by passing
35IN parameters
36
37 cstmt = con.prepareCall("{call P2('MyName', 123)}");
38
39 //STEP 4 : Executing The CallableStatement
40
41 cstmt.execute();
}
42 catch (SQLException e)
43 {
44 e.printStackTrace();
45 }
finally
46
{
47 //STEP 5 : Closing The DB Resources
48
49 //Closing the CallableStatement object
50
51 try
52 {
if(cstmt!=null)
53 {
54 cstmt.close();
55 cstmt=null;
56 }
57 }
catch (SQLException e)
58 {
59 e.printStackTrace();
60 }
61
62 //Closing the Connection object
63
64 try
{
65 if(con!=null)
66 {
67 con.close();
68 con=null;
69 }
}
70 catch (SQLException e)
71 {
72 e.printStackTrace();
73 }
}
74
}
75}
76
77
78
79
80
81
82
83
84
85
86
Java Program :
1 import java.sql.*;
2
public class CallableStatementExample
3 {
4 static
5 {
6 //STEP 1 : Registering The Driver Class
7
8 try
{
9 Class.forName("oracle.jdbc.driver.OracleDriver");
10 }
11 catch (ClassNotFoundException e)
12 {
System.out.println("Unable To Load The Driver class");
13 }
14 }
15
16 public static void main(String[] args)
17 {
18 Connection con = null;
19
CallableStatement cstmt = null;
20
21 try
22 {
23 //Database Credentials
24
25 String URL = "jdbc:oracle:thin:@localhost:1521:XE";
26
27 String username = "username";
28
String password = "password";
29
30
//STEP 2 : Creating The Connection Object
31
32 con = DriverManager.getConnection(URL, username, password);
33
34 //STEP 3 : Creating The CallableStatement Object
35
36 cstmt = con.prepareCall("{call P3(?, ?)}");
37
38 //Setting IN Parameter
39
40 cstmt.setInt(1, 123);
41
//Registering OUT parameters
42
43 cstmt.registerOutParameter(2, Types.VARCHAR);
44
45 //STEP 4 : Executing The CallableStatement
46
47 cstmt.execute();
48
49 //Retrieving the result returned by stored procedure
50
51 String grade = cstmt.getString(2);
52
53 System.out.println(grade);
}
54 catch (SQLException e)
55 {
56 e.printStackTrace();
}
57 finally
58 {
59 //STEP 5 : Closing The DB Resources
60
61 //Closing the CallableStatement object
62
63 try
{
64 if(cstmt!=null)
65 {
66 cstmt.close();
67 cstmt=null;
68 }
}
69 catch (SQLException e)
70 {
71 e.printStackTrace();
72 }
73
74 //Closing the Connection object
75
try
76 {
77 if(con!=null)
78 {
79 con.close();
con=null;
80 }
81 }
82 catch (SQLException e)
83 {
84 e.printStackTrace();
}
85 }
86 }
87 }
88
89
90
91
92
93
94
95
96
97
98
99
100
Java Program :
1 import java.sql.*;
2
3 public class CallableStatementExample
{
4 static
5 {
6 //STEP 1 : Registering The Driver Class
7
8 try
9 {
Class.forName("oracle.jdbc.driver.OracleDriver");
10 }
11 catch (ClassNotFoundException e)
12 {
13 System.out.println("Unable To Load The Driver class");
}
14 }
15
16 public static void main(String[] args)
17 {
18 Connection con = null;
19
20 CallableStatement cstmt = null;
21
try
22 {
23 //Database Credentials
24
25 String URL = "jdbc:oracle:thin:@localhost:1521:XE";
26
27 String username = "username";
28
29 String password = "password";
30
//STEP 2 : Creating The Connection Object
31
32
con = DriverManager.getConnection(URL, username, password);
33
34 //STEP 3 : Creating The CallableStatement Object
35
36 cstmt = con.prepareCall("{call P4(?, ?)}");
37
38 //Setting IN Parameters
39
40 cstmt.setInt(1, 123);
41
42 cstmt.setString(2, "LAST");
43
//Registering OUT parameters
44
45 cstmt.registerOutParameter(2, Types.VARCHAR);
46
47 //STEP 4 : Executing The CallableStatement
48
49 cstmt.execute();
50
51 //Retrieving OUT parameter
52
53 String grade = cstmt.getString(2);
54
55 System.out.println(grade);
}
56 catch (SQLException e)
57 {
e.printStackTrace();
58 }
59 finally
60 {
61 //STEP 5 : Closing The DB Resources
62
63 //Closing the CallableStatement object
64
try
65 {
66 if(cstmt!=null)
67 {
68 cstmt.close();
69 cstmt=null;
}
70 }
71 catch (SQLException e)
72 {
73 e.printStackTrace();
}
74
75
//Closing the Connection object
76
77 try
78 {
79 if(con!=null)
80 {
con.close();
81 con=null;
82 }
83 }
84 catch (SQLException e)
85 {
e.printStackTrace();
86 }
87 }
88 }
89 }
90
91
92
93
94
95
96
97
98
99
100
101
102
Why did JDBC come into existence?
In earlier days, the front-end applications are connected to the Databases using the functions
provided by the database vendors. For example, the C and C++ applications are connected to
the databases using a set of functions given by Oracle Corporation called orcl.h header
file. But, by this, the application becomes database dependent because every DB vendor
gives its own set of functions for communication. To overcome this, Microsoft with Simba
Technologies has provided us with the ODBC (Open Database Connectivity) community
with which we can connect and communicate with Database in an independent manner. Now
the general question arises like,
JDBC is a Java API which offers a natural Java interface for working with SQL.
What is JDBC?
Primarily, JDBC is an API (Application Programming Interface) or channel with which we
can connect Java applications to various databases. It is a Java API that accesses the data
from various kinds of Relational databases. It works with Java on various kinds of platforms
like Windows, Linux, MacOS etc.,
Before reading this tutorial, you need to have the basic knowledge of the Core Java concepts
like Abstraction, Interfaces, Collection Framework, Exception Handling etc.,
In this tutorial, we will discuss the JDBC Architecture, SQL Syntax, Environment set-up,
Drivers used, Connections, and Statements to query the Database. Let’s get started.
JDBC Architecture:
The JDBC API proposed will support both two-tier and three-tier architecture flows. So, in
general the architecture is comprised of two layers,
JDBC API provides transparent connectivity using the Driver Manager and database-specific
drivers.
JDBC Driver Manager provides assurance for the usage of the correct database driver to
access each data source.
1. JDBC API
1. The API provides standard methods and interfaces to smoothen the
communication with the database.
2. The process is simplified by providing two packages java.sql. * and
javax.sql.*.
3. The two packages exhibit WORA (Write Once Run Everywhere) capability
which contains both Java SE and Java EE support.
2. JDBC Driver Manager
1. The Driver Manager manages the list of database drivers.
2. It loads the database-specific Driver in Java application to establish the
connectivity with the database.
3. We use this Manager to make a call to the database.
3. JDBC Test Suite
1. Test Suite is used for Testing purposes (such as Insertion, deletion etc.,).
Why SQL?
1. Used by almost all Relational databases.
2. Allows users/programmers to write the database code independent on the underlying
database.
There is a fact that without learning the SQL we cannot understand the concepts of JDBC.
We will have a quick and basic overview of the SQL, SQL Operations often referred to as
CRUD Operations and their syntax.
1. CREATE Database
The CREATE DATABASE statement is generally used for creating a new database. The
syntax is,
2. DROP Database
The DROP DATABASE statement is generally used for deleting an existing database. The
syntax is,
The CREATE TABLE statement is used for creating a table within a database. The syntax is,
column_name1 coulumn_data_type,
column_name2 coulumn_data_type1,
);
4. DROP Table
The DROP TABLE statement is used for deleting an existing table in the database. The
syntax is,
5. INSERT Data
The INSERT statement is used for inserting the data into the table. It represents what new
data should appear in the respective columns. The syntax is,
6. SELECT Data
The SELECT statement is basically used to retrieve or fetch the data from the database. The
syntax is,
FROM table_name
WHERE conditions;
(OR)
SQL> SELECT *
FROM table_name
WHERE conditions;
7. UPDATE Data
The UPDATE statement is used in order to update the data. The syntax is,
WHERE conditions;
8. DELETE Data
The DELETE statement is used to delete the data from the tables. The syntax is,
WHERE conditions;
From the above details we can conclude that SQL provides us the capability to Create, Read,
Update and Delete the data from the databases. These operations are basically referred to as
CRUD Operations.
Environmental setup:
To start with JDBC, you need to set-up the environment by following the below steps. Please
note that the below environment set-up is subjected to only Windows platform.
1. Install Java
2. Install Database
3. Install Database Drivers
4. Set the Database Credentials
3. By the above installation or verification, you will automatically get the java.sql and
javax.sql packages along with the JDK you installed.
4. Installing the Target Database
1. The most important thing in JDBC is you need a Database where you create a
Database/Table and execute your own queries and modify them accordingly.
2. You have plenty of choices to install the most suitable database for you.
1. MySQL Database: It is an open-source database. It can be downloaded
from http://dev.mysql.com/downloads/mysql. In addition, also
download the MySQL Administrator from
https://dev.mysql.com/downloads/workbench/ and MySQL Query
Browser. Finally download and unzip the MySQL Connector/J from
https://dev.mysql.com/downloads/windows/installer/8.0.html.
Accordingly set the CLASSPATH variable C:\Program
Files\MySQL\mysql-connector-java-8.0.22\mysql-connector-java-
8.0.22.bin.jar. The Driver version may vary based on your installation.
3. Installing the Database Drivers
1. The latest JDK specification includes the JDBC-ODBC Bridge Drivers that
makes ODC drivers available for the programmers using the JDBC API for
Development and Testing purposes.
2. Now-a-days the most of the JDBC drivers are shipped along with the database
installation only.
4. Setting the Database Credentials
1. By Default, the administrator is set to root and provision is allowed to choose the
password.
2. By using the above root id and password, you can create another user id and password
of your choice.
3. After this, you can navigate to the installation directory of MySQL and create the
Database and Tables further for the experimental purposes.
Now, you guys are ready for experimenting with JDBC Let’s get started with the in-detail
concepts involved in JDBC API. Now, we will have a sample JDBC Program with which you
can get a complete idea on how to establish a connection to the database and perform the
operations.
JDBC Sample Code:
In this example, you will see how to implement he five basic steps to connect with the Oracle
database using JDBC in Java program.
A Type 1 JDBC driver translates the JDBC interface calls to ODBC calls. In this type, the
JDBC bridge is used to access the ODBC drivers that are installed on the Client machine.
There is a requirement that if we are using ODBC, we need to configure the Data source
name (i.e., name of the target database). This driver was proved useful in the early times as
most of the databases only supported the ODBC access. But in recent times, this type of
driver is only recommended for experimental purposes. As per the JDK8 specification, it will
be removed as it was considered as only the traditional solution. Oracle recommends us to
use the JDBC drivers provided by the vendors of the database only instead of this JDBC-
ODBC bridge.
sun.jdbc.odbc.JdbcOdbcDriver and this driver is close-source, that is it uses the native code
language rather than Java programming language.
Advantages:
Disadvantages:
The Type 2 JDBC Native-API driver translates the JDBC method calls to the Native calls of
the database Native-API. The Type 2 driver is similar to the JDBC-ODBC bridge driver
except that the ODBC driver is replaced with the Native API calls (C/C++ etc.). These API
calls are unique to the database. It is made sure that the native code part is targeted for the
specific database product. That is, it uses the client-side libraries of the database product.
This architecture eliminated the need for the ODBC driver configuration on the client
machine, and the native libraries that are to be used by the database are shipped along by the
vendors. This practice was quickly adopted by the DB vendors because of the
inexpensiveness and quickness of the reusability of drivers.
Advantages:
Disadvantages:
The Type 3 JDBC-Net Pure Java driver is also called a Middleware translation driver as it
uses the three-tier approach. In this, Java sends the JDBC interface calls to an intermediate
server. The intermediate server then connects to the database instead of the JDBC driver. In
this sort of driver, the JDBC clients use quality network sockets for communication with the
middleware application server. This type of communication in which the
intermediate/middleware is being used is also called a ‘PROXY’ server communication.
The Type 3 driver proved to be the 100% Java solution, but it does not gain much traction
then.
Advantages:
Disadvantages:
1. Network support requirement on the client machine.
2. Database-specific coding needs to be done in the intermediate/middle server.
3. Maintenance is expensive as we use the database-specific coding and the performance
also remains the same.
4. Type 4: JDBC Thin driver or 100% Pure Java driver
The Type 4 100% Pure Java Driver is also called Direct to database Pure Java Driver.
It translates the JDBC calls directly to the vendor-specific database calls. These
drivers are implemented specifically to a target database and are the most widely used
drivers now. These are written completely in Java and are platform-independent. The
portability is achieved as these drivers are part of the JVM. When compared to the
Type 3 drivers, it does not require any additional (intermediate server) layer to work
upon. The architecture is composed of all the logic of the direct database
communication within a single driver encapsulated in the JDBC API implementation.
This approach streamlines the easy development and deployment with only a single-
tier 100% pure Java package.
Advantages:
Disadvantages:
1. The Type 4 drivers are proprietary in nature aligned to their specific network
protocols.
2. These are again the database-specific drivers.
• Type 4 drivers can be used if you are preferring to use Oracle, Sybase, IBM
databases. This is suggested when you are using only one type of database in your
application.
• Type 3 drivers can be used if your Java application accesses multiple databases at the
same time.
• Type 2 drivers can be used in situations where the above two drivers Type 4, and
Type 3 drivers are not yet available.
• Type 1 driver as already mentioned as a not widely used driver. It can be used as a
traditional solution only for Development and Testing purposes.
JDBC Connections:
The JDBC Database Connections come into picture after the installation of the JDBC Driver
in the system.
The programming involved in establishing the JDBC Connection is simple and comprises
five steps depicted below.
Firstly, we should import the existing packages in our Java program/application. These
import statements help the Java Compiler where to find the classes you reference in the code.
By this, we can make sure that the JDBC API classes, sub-classes are available in the
program. Irrespective of JDBC Driver being installed, we import the below package, which is
the standard JDBC package that allows us to perform CRUD operations in our code.
import java.sql.*
We can import other classes based on the functionality we use in our Java program.
The JDBC API 4.0 mainly provides us with two standard java packages.
• java.sql.*
This package contains most of the standard JDBC functions used for Creating, Executing the
queries etc.,
• javax.sql.*
This package is a JDBC extension API which provides server-side data access and processing
in Java applications.
In order to make a connection to the database, we need to load/register the driver. We need to
register it only once per database in the program. To put it in a simple way,
registering/Loading the Driver means the process by which the Driver class file gets loaded
into the memory and hence, we can utilize it as a form of an implementation of the JDBC
interfaces. The need of registration is only once and the ways of registering it are two. It
entirely depends on the user to choose among the two.
• Class.forName()
This is the most common approach to register the driver. By using this, the Driver class can
be implicitly loaded at runtime into the memory. While Loading itself the Driver gets
registered automatically. The fact that it is most preferable is that it permits the user to make
the driver registration configurable and portable.
Here is an example,
• DriverManager.registerDriver()
This approach provides the users to register the drivers using the in-built class
DriverManager available in java.sql package. This acts as a mediator between the Java
Application and the target database.
public static void registerDriver(driver) – This method loads the Driver class of the
database and establishes the connection with the DB. If the driver is already registered, it will
not take any action. Two exceptions are thrown by this method.
ii. NullpointerException: If the Driver is not available or not set to the classpath.
Here is an example,
After the Driver has been loaded, the Connection should be created and established. This step
needs to be performed once the required packages are imported and the Drivers are loaded
and registered only. The getConnection() method in DriverManager class is used to get the
connection with Database. The getConnection() method is an overloaded method.
1. getConnection(url);
2. getConnection(url, username, password);
Connection Interface:
• A Connection is nothing but a session between Java application and the Database.
• Its available in the java.sql package.
• It is an interface with a factory of Statement, PreparedStatement, MetaData etc.,
• It also provides methods related to the Transaction Management like commit(),
rollback() etc.,
• The Driver Manager class acts as an interface between the user and the drivers.
• It keeps track of all the set of drivers and maintains the registered drivers and also
handles the establishment of connection between the database and the driver.
Here is an example,
Connection con = DriverManager.getConnection(jdbc:thin:@localhost:1521:xe, System,
pass@123);
The below table lists the connection URL for various databases,
Note that the Database URL is an address that usually points to the user’s database.
After the establishment of the database connection, now user can interact with the database.
For this, we need to create a Statement to perform the SQL query and then execute the
statement.
• Creating a Statement:
We use the methods from Connection class to create the queries. As part of the java.sql
package we have three statement interfaces available.
• Statement
It is used to implement simple statements with no parameters and return the ResultSet object.
• Prepared Statement
This is extended from the Statement interface with extra features of using the parameterized
statements and pre-compiled SQL queries. The performance of this is high as it pre-compiles
the queries before-hand.
• Callable Statement
This is extended from the PreparedStatement interface with extra features of implementing
the parameterized SQL statements to invoke and execute the Stored procedures or functions
in the database.
The query developed can be executed for updating/inserting in the database and retrieving the
data. There are four important methods for executing the SQL query.
This is the method in the Statement interface and is used to retrieve the results from the
database. It is similar to the SELECT query in SQL.
This is used for specified operations like INSERT, UPDATE, DELETE (DML statements)
and DDL statements that return nothing. It is mostly used to insert and update the record
entries in the database.
This is used to execute the SQL query. It returns TRUE if it is a SELECT query. It returns
FALSE if t s UPDATE or INSERT query.
• int[] executeBatch ()
This method is used to execute the batch of SQL queries. If all the queries are successful
then, it returns the array of update counts. It is mostly used to insert or update the records in
bulk.
The executeQuery() method in the Statement interface will return the results in the form of a
ResultSet Object. The returned object will never be NULL even if there are no matching
records in the database.
ResultSetrs = statement1.executeQuery(QUERY);
This method is only used for SELECT query. If any INSERT/UPDATE query is given as
input, then it throws the SQLException saying that ‘this method cannot be used for
UPDATE’. ResultSet is an Enumerator Object.
conn.close();
After Java 7, the JDBC connections can be automatically closed if we use the try-catch block.
This feature is called Automatic resource management.
JDBC Statements:
JDBC Statements are used to execute the SQL queries. The JDBC API provides us with three
types of statements.
1. Statement interface
• The Statement interface is used in-order to get the general-purpose access to the target
database.
• It is proven as useful when we have static SQL queries which needs to be run at run
time.
• No parameters can be sent in to retrieve the results based on the conditions.
Here is an example,
try {
statement1 = conn.createStatement();
} catch (SQLExcetion e) {
} finally {
statement1.close();
• After the creation of the statement object the user needs to execute it. We can use any
of the three below methods to do that operation.
o booleanexecute(String sql)
o int execcuteUpdate(String sql)
o ResultSetexecuteQuery(String sql)
Here is an example,
PreparedStatementpStatement = null;
try {
pStatement = conn.prepapredStatement(SQLStatement);
} catch (SQLException e) {
} finally {
conn.close();
Here is an example,
CallableStatementcStatement = null;
try {
cStatement = conn.prepareCall(SQLStatement);
} catch (SQLException e) {
} finally {
conn.close();
• The Callable Statement with only IN parameters behaves the same as the
PreparedStaement only.
• When the SQL statement has either OUT or INOUT parameters, it is mandatory that
we need to employ the registerOutParameter() method.
• The registerOutParamter() is generally used to bind the JDBC data type to the data
type which the Stored Procedure is expected to return.
Note: Ensure proper clean-up of the resources if you are using the Java versions below 7.
After version 7, Java try with resources block ensures that the resources opened are
automatically closed when not used.
XML Basics
XML stands for Extensible Markup Language and is a text-based markup language
derived from Standard Generalized Markup Language (SGML).
XML is a software- and hardware-independent tool for storing and transporting data.
XML tags identify the data and are used to store and organize the data, rather than
specifying how to display it like HTML tags, which are used to display the data. XML
is not going to replace HTML in the near future, but it introduces new possibilities by
adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of
systems and solutions:
XML is extensible: XML allows you to create your own self-descriptive tags, or
language, that suits your application.
XML carries the data, does not present it: XML allows you to store the data
irrespective of how it will be presented.
XML is a public standard: XML was developed by an organization called the
World Wide Web Consortium (W3C) and is available as an open standard.
XML Usage
XML can work behind the scene to simplify the creation of HTML documents for
large web sites.
XML can be used to exchange the information between organizations and
systems.
XML can be used for offloading and reloading of databases.
XML can be used to store and arrange the data, which can customize your data
handling needs.
XML can easily be merged with style sheets to create almost any desired
output.
Virtually, any type of data can be expressed as an XML document.
1
The Difference between XML and HTML
XML was designed to carry data - with focus on what data is
HTML was designed to display data - with focus on how data looks
XML tags are not predefined like HTML tags
XML documents form a tree structure that starts at "the root" and branches to
"the leaves".
XML Syntax:
<?xml version="1.0"?>
<contact_info>
<name>Rajesh</name>
<company>TCS</company>
<phone>9333332354</phone>
</contact_info>
You can notice there are two kinds of information in the above example:
The following diagram depicts the syntax rules to write different types of markup and
text in an XML document.
2
)
XML Declaration
The XML document can optionally have an XML declaration. It is written as below:
Where version is the XML version and encoding specifies the character encoding used
in the document.
<element>
<element>....</element>
<element/>
Nesting of elements:
An XML-element can contain multiple XML-elements as its children, but the children
elements must not overlap. i.e., an end tag of an element must have the same name
as that of the most recent unmatched start tag.
3
<?xml version="1.0"?>
<contact_info>
<company>TCS
<contact_info>
</company>
<?xml version="1.0"?>
<contact_info>
<company>TCS</company>
<contact_info>
Root element:
An XML document can have only one root element. For example, following is not a
correct XML document, because both the x and y elements occur at the top level
without a root element:
<x>...</x>
<y>...</y>
<root>
<x>...</x>
<y>...</y>
</root>
Case sensitivity:
The names of XML-elements are case-sensitive. That means the name of the start
and the end elements need to be exactly in the same case.
Attributes
An attribute specifies a single property for the element, using a name/value pair.
An XML-element can have one or more attributes. For example:
<a href="http://www.tutorialspoint.com/">Tutorialspoint!</a>
4
Syntax Rules for XML Attributes
Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are
considered two different XML attributes.
Same attribute cannot have two values in a syntax. The following example shows
incorrect syntax because the attribute b is specified twice:
<a b="x" c="y" b="z">....</a>
Attribute names are defined without quotation marks, whereas attribute values must
always appear in quotation marks. Following example demonstrates incorrect xml
syntax:
<a b=x>....</a>
In the above syntax, the attribute value is not defined in quotation marks.
XML References
References usually allow you to add or include additional text or markup in an XML
document. References always begin with the symbol "&" ,which is a reserved
character and end with the symbol ";". XML has two types of references:
Entity References: An entity reference contains a name between the start and the
end delimiters. For example & where amp is name. The name refers to a
predefined string of text and/or markup.
XML Text
5
not allowed character replacement-entity character description
6
An Example XML Document
--------------------------------------------------------------------------
---------------------------------------------------------------
An XML tree starts at a root element and branches from the root to child elements.
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
The terms parent, child, and sibling are used to describe the relationships between
elements.
Parents have children. Children have parents. Siblings are children on the same
level (brothers and sisters).
7
XML Namespaces
Name Conflicts
In XML, element names are defined by the developer. This often results in a conflict when
trying to mix XML documents from different XML applications.
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
If these XML fragments were added together, there would be a name conflict. Both
contain a <table> element, but the elements have different content and meaning.
A user or an XML application will not know how to handle these differences.
This XML carries information about an HTML table, and a piece of furniture:
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
In the example above, there will be no conflict because the two <table> elements have
different names.
8
XML Namespaces - The xmlns Attribute
When using prefixes in XML, a namespace for the prefix must be defined.
The namespace can be defined by an xmlns attribute in the start tag of an element.
-----------------------------------------------------
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="https://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
--------------------------------------------------
The xmlns attribute in the first <table> element gives the h: prefix a qualified
namespace.
The xmlns attribute in the second <table> element gives the f: prefix a qualified
namespace.
When a namespace is defined for an element, all child elements with the same prefix are
associated with the same namespace.
9
XML Validator
Example 1:
<?xml version=”1.0”?>
<book>
<title>Java</Title>
<author>James</book>
<pirce>570
</author>
The above XML document is not a well formed document. Reasons given below...
tags are not matching <title> … </Title>
There is no proper nesting <author>….</book>
Tag doesn’t closed <price>
Example 2:
<?xml version=”1.0”?>
<book>
<title>Java</title>
<author>James</author>
<price>500</price>
</book>
A "well formed" XML document is not the same as a "valid" XML document.
A "valid" XML document must be well formed. In addition, it must conform to a document
type definition.
10
There are two different document type definitions that can be used with XML:
A document type definition defines the rules and the legal elements and attributes for an
XML document.
--------------------------------------------------------------------------
<!DOCTYPE book
[
<!ELEMENT book
(title,author,price)> <!ELEMENT
title (#PCDATA)> <!ELEMENT author
(#PCDATA)> <!ELEMENT price
(#PCDATA)> ]>
-------------------------------------------------------------
!DOCTYPE book defines that the root element of the document is book
!ELEMENT book defines that the book element must contain the elements:
"title, author, price”
!ELEMENT title defines the title element to be of type "#PCDATA"
!ELEMENT author defines the author element to be of type "#PCDATA"
!ELEMENT price defines the price element to be of type "#PCDATA"
2) External DTD.
11
1) Internal / Embedded DTD.
<student>
<id>543</id>
<name>Ravi</name>
<age>21</age>
<addr>Guntur</addr>
<email>[email protected]</email>
<ph>9855555</ph>
<gender>male</gender>
</student>
2) External DTD.
If the above xml code follows the exact rules defined in DTD then we can conclude
that our xml document is a valid document. Otherwise it is an invalid document.
12
When to Use a DTD/Schema?
With a DTD, independent groups of people can agree to use a standard DTD for
interchanging data.
With a DTD, you can verify that the data you receive from the outside world is valid.
You can also use a DTD to verify your own data.
XML Schema
An XML Schema describes the structure of an XML document, just like a DTD.
An XML document validated against an XML Schema is both "Well Formed" and
"Valid".
Syntax
You need to declare a schema in your XML document as follows:
<xs:schema>
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="price" type="xs:integer"/>
<xs:element name="edition" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
13
Example:
---------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com" elementFormDefault="qualified">
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:integer"/>
<xs:element name="addr">
<xs:complexType>
<xs:sequence>
<xs:element name="city" type="xs:string"/>
<xs:element name="pincode" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="ph" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
-----------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
If the above xml code follows the exact rules defined in “student.xsd” then we can
conclude that our xml document is a valid document. Otherwise it is an invalid
document.
14
XSLT Introduction
XSLT stands for XSL Transformations. CSS = Style Sheets for HTML
HTML uses predefined tags. The meaning of, and how to display each tag is well
understood.
XML does not use predefined tags, and therefore the meaning of each tag is not well
understood.
A <table> element could indicate an HTML table, a piece of furniture, or something else -
and browsers do not know how to display it!
What is XSLT?
Example:
<book_store>
<book>
<title>JAVA</title>
<author>James</author>
</book>
<book>
<title>DBMS</title>
<author>Raghu</author>
</book>
</book_store>
Save the above code as “book.xml” and prepare the style sheet for this xml file.
15
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Book Details</h2>
<table border="1">
<tr>
<th>Title</th>
<th>Author</th>
</tr>
<xsl:for-each select="book_store/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Now open “book.xml” file through any browser, observe the output as given below
Title Author
Java James
DBMS Raghu
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
It presents an HTML document as a tree-structure.
The XML DOM defines a standard way for accessing and manipulating XML documents. It
presents an XML document as a tree-structure.
16
Example:
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'Hello World!'">Click Me!
</button>
</body>
</html>
In other words: The XML DOM is a standard for how to get, change, add, or
delete XML elements.
Programming Interface
The DOM models XML as a set of node objects. The nodes can be accessed with
JavaScript or other programming languages.
The programming interface to the DOM is defined by a set standard properties and
methods.
Methods are often referred to as something that is done (i.e. delete "book").
17
XML DOM Methods
DOM Example:
<html>
<body>
<script>
function myfun()
{
var text, parser, xmlDoc;
text = "<bookstore><book>" +
"<title>Java</title>" +
"<author>James</author>" +
"<year>1991</year>" +
"<book>" +
"<title>DBMS</title>" +
"<author>Raghu</author>" +
"<year>1970</year>" +
"</book>"+
"</book></bookstore>";
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>
Output:
1991
Example Explained
18