JDBC
JDBC
● JDBC is a Java standard that provides the interface for connecting programs in Java to
relational databases.
● The JDBC standard is defined by Sun Microsystems and implemented through the standard
java.sql interfaces.
● 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:
Making a connection to a database
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
Viewing & Modifying the resulting records
● JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
RDB.
Design of JDBC
● It has been designed to provide database independence for developers.
● JDBC is designed to provide a database-neutral API for accessing relational databases from
different vendors.
● JDBC has been designed in such a way that the database application can use the same
methods to access data regardless of the underlying database product.
● JDBC was developed to work with the most common type of database: the relational
database.
● JDBC consists of two layers: JDBC API and JDBC Driver Manager API.
● The JDBC API is the top layer and is the programming interface in Java to SQL.
● The JDBC API communicates with the JDBC Driver Manager API, sending it various SQL
statements.
● The manager communicates with the third party that actually connect to the database and
return the information from the query.
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: provides the application-to-JDBC Manager connection.
JDBC Driver Manager API: supports the JDBC Manager-to-Driver Connection.
● JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases(use more than one kind of processor or cores).
● JDBC driver manager ensures that the correct driver is used to access each data source.
JDBC Components:
Driver Manager: 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 Driver Manager objects, which manages
objects of this type.
ResultSet: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects.
SQLException: This class handles any errors that occur in a database application.
JDBC configuration
# JDBC Driver: It implements defined interfaces in the JDBC API for interacting with your
database server.
For example, using JDBC drivers you can open database connections and interact with it by
sending SQL or database commands then receiving results with Java.
● These drivers are provided by the database vendors and used in the same manner as the
JDBC-ODBC Bridge.
● The vendor-specific driver must be installed on each client machine.
● If we change the Database we have to change the native API as it is specific to a database
e.g. Oracle Call Interface (OCI) driver
Type 3: JDBC-Net pure Java:
● Three-tier approach is used to access databases.
● The JDBC clients use standard network sockets(endpoints of a 2-way communication link between
2 programs running on the network) to communicate with middleware application server.
● The socket information is then translated into the call format required by the DBMS, and
forwarded to the database server.
● This kind of driver is extremely flexible, since it requires no code installed on the client and
a single driver can actually provide access to multiple databases.
● To use the standard JDBC package, which allows you to select, insert, update, and delete data in
SQL tables, add the following imports to your source code:
import java.sql.* ;
Class.forName(): dynamically load the driver's class file into memory, which automatically registers it.
This method is preferable because it allows you to make the driver registration configurable and portable.
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
jdbc:oracle:thin:@root:1521:EMP
Now you have to call getConnection() method with appropriate username and password to get a
Connection object as follows:
jdbc:oracle:driver:username/password@databasepath
So the above connection can be created as follows:
String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = DriverManager.getConnection(URL);
A Properties object holds a set of keyword-value pairs. It's used to pass driver properties to the
driver during a call to the getConnection() method.
● The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and
properties that enable you to send SQL or PL/SQL commands and receive data from your database.
● They also define methods that help bridge data type differences between Java and SQL data types used in a
database.
boolean execute(String SQL) : Returns true if a ResultSet object can be retrieved; otherwise, it returns false.
int executeUpdate(String SQL) : Returns no. rows affected by the execution of the SQL statement.
� All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker.
� You must supply values for every parameter before executing the SQL statement.
� 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.
� If you forget to supply the values, you will receive SQLException.
� The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java
array ,indices, which start at 0.
� execute(), executeQuery() and executeUpdate() also work with the PreparedStatement object.
� However, the methods are modified to use SQL statements that can take input the parameters.
Parameter Description
A parameter whose value is unknown when the SQL statement is created. You bind values to IN
IN
parameters with the setABC() methods.
A parameter whose value is supplied by the SQL statement it returns. You retrieve values from
OUT
the OUT parameters with the getABC() methods.
A parameter that provides both input and output values. You bind variables with the setABC()
INOUT
methods and retrieve values with the getABC() methods.
The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a
CallableStatement object based on the preceding stored procedure:
ResultSet
● The SQL statements that read data from a database query return the data in a result set.
● The SELECT statement is the standard way to select rows from a database and view them in a result set.
● The java.sql.ResultSet interface represents the result set of a database query.
● A ResultSet object maintains a cursor that points to the current row in the result set.
● The term "result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories:
Navigational methods: used to move the cursor around.
Get methods:used to view the data in the columns of the current row being pointed to by the cursor.
Update methods: used to update the data in the columns of the current row. The updates can then be updated in the
underlying database as well.
JDBC provides following connection methods to create statements with desired ResultSet:
on the basis of ResultSet cursor movement there are two types of ResultSets
ii)scrollable ResultSets:
Allow the users to interact with the data in both forward and backward directions.
ii)updatable ResultSet:
Allow user to update it’s content.
Public static final int CONCUR_UPDATABLE.
If you want to specify particular ResultSet type in JDBC applications then specify the type of ResultSet object at the
time of creation of statement object.
e.g.
public statement createStatement(int forwardonly/ ScrollSensitive/ ScrollInsensitive,int
readonly/updatable)throws SQLException
● In case of SrollSensitive ResultSet object, after performing modifications in Database to reflect those
modifications into the ResultSet object we have to refresh each and every row in ResultSet object.
Note:If the int value is positive then cursor will move in forward direction, if it is negative then cursor will
move in backward direction.
● In order to make temporary insertion as permanent insertion in the ResultSet object and database
public void insertRow()
Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
while(rs.next())
{
System.out.println(rs.getString(“eno”)+” “+ rs.getString(“ename”)+” “+rs.getString(“esal”));
}
System.out.println(“application in pausing state”);
System.out.println(“perform updations at database”);
System.in.read();
rs.beforeFirst();
System.out.println(“data after updations”);
System.out.println(“——————–“);
System.out.println(“ENO ENAME ESAL”);
System.out.println(“——————–“);
while(rs.next())
{
rs.refreshRow();
System.out.println(rs.getString(“eno”)+” “+rs.getString(“ename”)+” “+rs.getString(“esal”));
}
con.close();
}
}
Example
package com.visualbuilder;
import java.sql.*;
public class Up
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:33
06/test","root","root");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.
CONCUR_UPDATABLE);
while(rs.next())
{
System.out.print("Id is " + rs.getInt("id"));
System.out.println(" Name is "+rs.getString("name"));
}
rs.absolute(1);
rs.updateString(2,"Visual Builder");
rs.updateRow();
rs.beforeFirst();
System.out.println("After Updation");
while(rs.next())
{
System.out.print("Id is " + rs.getInt("id"));
System.out.println(" Name is "+rs.getString("name"));
}
stmt.close();
con.close();
}
catch(Exception e)
{
}
}
}
Output:-
Id is 1 Name is Sun java
Id is 2 Name is Visual Builder
Id is 3 Name is Eclipse
Id is 4 Name is IBM
Id is 5 Name is Jakarta
After Updation
Id is 1 Name is Visual Builder
Id is 2 Name is Visual Builder
Id is 3 Name is Eclipse
Id is 4 Name is IBM
Id is 5 Name is Jakarta
import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
String adm_no=req.getParameter("adm_no");
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test",”root”,”root”)
;
Statement stat=con.createStatement();
ResultSet rs=stat.executeQuery("Select * from SchoolClasses Where
Admission_No="+adm_no);
pr.println("<HTML>");
pr.println("<Head><Title>Using JDBC In Servlet</Title></Head>");
pr.println("<Body>");
pr.println("<Center><H1>Using JDBC In Servlet</h1><HR><BR>");
pr.println("<Table Border=1>");
pr.println("<Tr><Th>Class</Th><Th>RollNo</Th><Th>Name</Th><Th>Father's
Name</Th><Th>DOB</Th><Th>City</Th></Tr>");
while(rs.next())
{
String clas=rs.getString("Class");
String rollno=rs.getString("Roll_No");
String name=rs.getString("Name");
String fname=rs.getString("Father_Name");
String dob=rs.getString("DOB");
String city=rs.getString("City");
pr.println("<Tr><Td>"+clas+"</Td>");
pr.println("<Td>"+rollno+"</Td>");
pr.println("<Td>"+name+"</Td>");
pr.println("<Td>"+fname+"</Td>");
pr.println("<Td>"+dob+"</Td>");
pr.println("<Td>"+city+"</Td></Tr>");
}
pr.println("</Table></Center>");
pr.println("</Body></HTML>");
}
catch(Exception e)
{
pr.println(e);
}
}
}
Row sets
● A Row Set object is a java bean component and extends the ResultSet interface
● Thus, it has a set of JavaBeans properties and follows the JavaBeans event model.
● Allows to establish its own database connection and to execute its own query in order to fill itself with data.
Types of Rowset
1. Connected Rowset:- It is connected to the database connection object like the Resultset. e.g. JDBCRowSet
2. Disconnected RowSet:- It connects to the database whenever required and after finishing the interaction they close
the database connection.
Passing the ResultSet:- In this approach the data is populated in the object and then you can retrieve the data by
using the get methods as we did in case of the ResultSet.
Exmple:-
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“select * from employee”);
JdbcRowSet jdbcRs = new JdbcRowSetImpl(rs);
Creating the default object:- This approach is useful if you want to set the data sources dynamically. In this
approach the Database URL, username and password is explicitly set in the RowSetObject.
Exmple:-
JdbcRowSet jdbcRs = new JdbcRowSetImpl();
jdbcRs.setUsername("user");
jdbcRs.setPassword("password");
jdbcRs.setUrl("jdbc:mySubprotocol:mySubname");
jdbcRs.setCommand("select * from EMP ");
jdbcRs.execute();
import java.sql.*;
import com.sun.rowset.JdbcRowSetImpl;
public class JDBCRowSetExample
{
public static void main(String[] args) throws SQLException
{
Metadata
Data about the data is called as metadata.
In JDBC there are two types of metadata.
1.Database metadata
2.ResultSet metadata.
JDBC Meta Data is the collective information about the data structure and property of a column available in table.
The meta data of any table tells you the name of the columns, datatype of column and constraint used to enter the
value of data into column of the table.
Example
import java.sql.*;
public class Jb
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”,root,root);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from person");
ResultSetMetaData metaData = rs.getMetaData();
Output:-
Table Name: person
Field Size DataTypes
id 2 VARCHAR
cname 50 VARCHAR
dob 10 DATE
Transaction
● Consistency ensures bringing the database from one consistent state to another consistent state.
● Durability means once a transaction has been committed, it will remain so, even in the event of errors, power
loss etc.
Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is committed by default.
void commit() commits the transaction.
void rollback() cancels the transaction.