Java JDBC (Unit-4)
Java JDBC (Unit-4)
TECHNOLOGY
Contents
Java Database Connectivity (JDBC)
Merging Data from Multiple Tables
Joining, Manipulating, Databases with JDBC
Prepared Statements, Processing Stored Procedures
Transaction
MetaData
JDBC (Java Database Connectivity)
• It’s a java API to connect & execute query with DB
• JDBC API uses JDBC drivers to connect with DB.
Why use JDBC
• Before JDBC, ODBC API was the database
API to connect and execute query with DB.
• But, ODBC API uses ODBC driver which is
written in C language (i.e. platform
dependent and unsecured).
Advantages:
• easy to use.
• can be easily connected to any DB.
Disadvantages:
• Performance degraded because JDBC method
call is converted into the ODBC function calls.
Advantage:
• performance upgraded than JDBC-
ODBC bridge driver.
Disadvantage:
• The Native driver needs to be installed on
the each client machine.
Disadvantages:
• Network support is required on client machine.
• Requires DB-specific coding to be done in middle
tier.
• Maintenance of Network Protocol driver becomes
costly because it requires DB-specific coding to be
done in the middle tier.
4) Type-4: Thin driver
Disadvantage:
• Drivers depends on the Database.
5 Steps to connect to the DB in java
1. Register the driver class
2. Creating
connection
3. Creating statement
4. Executing queries
5. Closing connection
1) Register the driver class
• The forName() method of class Class is used
to
register the driver class. It dynamically load
the driver class.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
• The getConnection() method of
DriverManager class is used to establish
connection with the DB.
Connection
con=DriverManager.getConnection( "jdbc:oracle:thi
n:@localhost:1521:xe","system","pa ssword");
3) Create the Statement object
• The createStatement() method of Connection
interface is used to create statement.
• The object of statement is responsible to execute
SQL & return the results by using the ResultSet
object.
"+rs.getString(2));
}//while
C) To Delete record
….
….
Statement st = conn.createStatement();
String str="delete from student where sid=103
"; int r=st.executeUpdate(str);
System.out.println(r+"\t Rows Deleted Successfully!!!");
System.out.println(“\n ======Display Result========“);
ResultSet rs = st.executeQuery("SELECT * from
student");
// Retrieve the
results
while(rs.next()){
System.out.println(rs
.getInt(1)+" }
"+rs.getString(2));
}//while
D) To Update record
Statement st = conn.createStatement();
String str="update student set sname='Abhineet' where
sid=101 ";
int r=st.executeUpdate(str);
System.out.println(r+"\t Rows Updated Successfully!!!");
ResultSet rs = st.executeQuery("SELECT * from
student");
// Retrieve the results
while(rs.next()){
System.out.println(rs
.getInt(1)+"
"+rs.getString(2));
}//while
PreparedStatement interface
• It is a subinterface of Statement.
• Used to execute parameterized query. It accepts
input parameters at runtime.
• A SQL statement is precompiled and stored in a
PreparedStatement object
• Its object is created using the prepareStatement()
method of Connection interface, as:
String query = “insert into emp values(? ,?)”;
PreparedStatement ps =
con.prepareStatement(query);
ps.setInt(1,105);
ps.setString(2,”Meenal”);
int n = ps.executeUpdate();
Use of PreparedStatement:
Improves performance:
- can be used to represent a precompiled query,
which can be executed multiple times.
Disadvantage:
It can represent only one SQL statement at a
time.
Example of PreparedStatement interface that inserts the record
import java.sql.*;
public class insertPST
{
public static void main(String[] args) {
try{ Class.forName("com.mysql.jdbc.Dri
ver"); Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/
kiet","root",""); String query="insert into student values(?,?)";
PreparedStatement pst=con.prepareStatement(query);
pst.setInt(1,103);
pst.setString(2, "Bhanu");
int
r=pst.executeUpdate();
System.out.println(r+"\t Rows Inserted
Successfully!!!"); ResultSet rs =
pst.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt(1)+"
"+rs.getString(2)); con.close();
}catch(Exception e) {
System.out.println(e);}
Example of PreparedStatement interface that updates/deletes/retrieves the record
String query="update student set sname=? where sid=?";
PreparedStatement pst=con.prepareStatement(query);
pst.setInt(2,103);
pst.setString(1, "Bhavya");
int r=pst.executeUpdate();
System.out.println(r+"\t Rows Updated Successfully!!!");
CallableStatement
cs=con.prepareCall("{call Proc_Name(?,?)}");
Super interface for Prepared and Callable extends Statement extends PreparedStatement (sub-
Statement (sub- interface) interface)
PreparedStatement CallableStatement
ps=con.prepareStatemen cs=conn.prepareCall("{call
stmt = conn.createStatement(); t ("insert into studentDiet getbranch(?,?)}");
values(?,?,?)");
• used for reading content of DB • used for altering the DBs • If you dont know which
• Statement: DROP, INSERT, method to be used for executing
• The output will be in the form UPDATE, DELETE used. SQL statements, this method
of ResultSet. can be used.
• Output will be in the form of
int. • This will return a boolean.
• Generally SELECT
statement is used. • This int value denotes the number
• TRUE indicates the result is a
of rows affected by the query. ResultSet and FALSE indicates it
has the int value which denotes
number of rows affected by the
query.
Method Semantics
first() Moves cursor to first row Moves
last() cursor to last row Moves cursor to
next() next row
previous() Moves cursor
afterLast() to just before the first row
Moves cursor
absolute(int) Moves cursorthe
to just after to last
a row index. If positive –
row
counting from the front, if negative – from the
back
relative(int) Moves cursor a relative number of rows, positive or
negative from the current position
getXXX(…) methods
It take a column name the number of the
or column
column numbers start at 1 & go from left to right
For example:
rs.getString(“sname”):
returns the student name as a String
in fact, we can get any of the SQL types with
getString(…) and it will automatically be
converted to a String
Transactions
It is the propagation of one or more changes to DB Ex:
creating/updating/deleting a record from the table.
import java.sql.*;
public class databaseMD {
public static void main(String[] args)
{ try{ Class.forName("com.mysql.jdbc.Dr
iver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/kiet","root","");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println ("getDatabaseProductName:"+dbmd.getDatabaseProductName());
System.out.println("getDatabaseProductVersion():"+dbmd.getDatabaseProductVersion());
System.out.println("getDriverName():"+dbmd.getDriverName());
System.out.println("getDriverVersion():"+dbmd.getDriverVersion());
System.out.println("getURL():"+dbmd.getURL());
System.out.println("getUserName():"+dbmd.getUserName());
con.close();
}catch(Exception e)
{
System.out.println(e);
}}}
OUTPUT:
Than
k
You