Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 14

04-April-2024

Jdbc Introduction
JDbc stands for Java Database Connectivity.JDBC is API to connect and execute the
query with the database.
There are four type of drivers:
01)JDBC-ODBC Bridge Driver.
02)Native Driver
03)Network Protocal Driver
04)Thin Driver

We can use JDBC API to access data stored in any relational database.we can
save,update,delete and fetch or retrive data from database.

JDBC Driver:
01)JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.The JDBC-
ODBC bridge driver converts JDBC method calls into ODBC
function calls.
Oracle does't support this driver from java 8.Oracle recommends that you are useing
JDBC drivers provided by the vendor.

02)Native API library


This driver uses client-side libraries of the database.This driver converts jdbc
calls into native calls of the database API.

03)Network Protocal driver


This protocal driver uses middleware that converts jdbc calls directly or
indirectly into vendor database protocal.

04)Thin driver:
This driver converts jdbc calls into vendor database protocal.

Java Database Connectivity Steps:


There are 5 steps to connect any java application with the database using jdbc.
These steps are as follows
01)Register the driver class
02)Create connection
03)Create Statement
04)Execute Queries
05)Close connection

01)Register the driver class


The forName() method of class is used to register the driver class.
Syntax of forName() method:
public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class


Here, Java Program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver")

02)Create the connection object


The getConnection() method of DriverManager class is used to establish connection
with the database.
Syntax of getConnection() method:
01)public static Connection getConnection(String url)throws SQLException
02)public static Connection getConnection(String url,String name,String password)

Example to establish connection with the Oracle database


Connection
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott
","tiger")

03)Create the Statement object:


createStatement() method of Connection interface is used to create statement.The
object of statement
is responsible to execute queries with the database.
Syntax createStatement() method:
public Statement createStatement()throws SQLException

Example to create the statement object


Statement statement=connection.createStatement();

04)Execute query
executeQuery() method of Statement interface is used to execute queries to
database.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet resultset=statement.executeQuery("select * from emp");
while(resultset.next()){
System.out.println(resultset.getInt(1)+" "+resultset.getString(2));
}

05)Close the connection object:


By closing connection object statement and resultSet will be closed automatically.
Syntax:
public void close()throws SQLException
Example
connection.close();

what is difference between Editor and IDE?


Editor :: Just provides development environment(Mostly env..to write the code)
eg: editplus, notepad, notepad++, wordpad etc
IDE(Integrated Development Environment):: It gives multiple facilities that
required for developing and
building the application. i.e we can write the code, compile the code,test the
code,pack the code,debug code etc
eg::Eclipse(free), myeclipse(commercial),Intellij,Visual studio,NetBeans,Jcreator,
and etc.

Eclipse IDE is popular in domain because


a)It is free IDE
b)Developer are habituated with this IDE from so many days.

Eclipse
type: IDE gor java
version:2024-03
vendor :: Eclipse Organization
open source(free IDE)
variants :: Eclipse SDK(only for standalone apps development)
Eclise JEE(for standalone, advanced applications development)

Installation :: Download as zip file and extract the zip file installation

Procedure to develop JDBC App() using eclipse IDE


step1)download and install eclipse IDE
step2)launch eclipse IDE using eclipse.exe file(collect from zip file extraction)
and choose workspace folder.
step3)create Java Project in Eclipse IDE
File -->new -->project -->name::JDBCProj1 -->next --> finish.
step4) add ojdbc6.jar file to BUILDPATH/CLASSPATH od the project
Right Click on Project--> buildpath --> configure build path --> Libraries
tab --> class path -->
add external jar files --> browse and select the jar file.
step5) create java pkg in the "src" folder of the project
right click on "src" folder --> new --> package -->
name::com.fg.jdbc --> next --> finish
note1::It is recommended to place every class in package
note2::It is recommended to take 3 words in package name having self
description
eg:com.fg.jdbc, org.mit.jdbc, mit.cs.jdbc, mit.training.jdbc

To create package from java use package<packagename>;


To import package use import<package name>;
step6) develop the app by adding the class to the package
Right click on package name --> new --> class -->

# tnsnames.ora Network Configuration File: C:\app\don\product\11.2.0\dbhome_1\


network\admin\tnsnames.ora

Write a jdbc App to establish connection with Oracle Database s/w using type4 jdbc
driver s/w.
package com.fg.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionTest {


public static void main(String[] args)throws Exception {
//1.Register JDBC driver s/w with Driver Manager service
Class.forName("oracle.jdbc.driver.OracleDriver");

//2.Establish the connection with databse software


Connection
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","sco
tt","tiger");

if(connection==null)
System.out.println("Connection is not established with the
database software");
else
System.out.println("Connection is established with the database
software");
}
}

(1)DriverManager.getConnection(-,-) uses "jdbc:oracle:thin" of given jdbc url to


pickup the registered oracle
thin driver software from DriverManager service.

(2)The pickup jdbc driver software establish the connection with "orcl" logical DB
of oracle DB s/w that
is running on 1521 port number of current computer.In that process it uses the
given dbuser name and password for
authentication.
(3)DriverManager.getConnection(-,-) returns jdbc connection object back to
application representing the
connectivity between java app and Database software.we can use that jdbc connection
object to check
wheather connection with database software established or not.

Write a Java App having jdbc code to get all the records of STUDENT db table.
step1) keep the following software setup ready
jdk 1.8+
oracle 11g
step2) create db table "Student" having records using SQL promt or sql plus
start button -->search for SQL --> Run SQL Command Line -->
sql>connect
Enter user-name: scott
Enter password:

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> create table student(sno number(5) primary key, sname varchar2(20), sadd
varchar2(20), avg float);

Table created.

SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
SNO NOT NULL NUMBER(5)
SNAME VARCHAR2(20)
SADD VARCHAR2(20)
AVG FLOAT(126)

SQL> insert into student values(101,'raja','hyderbad',67.88);

1 row created.

SQL> insert into student values(102,'rajesh','vizag',27.88);

1 row created.

SQL> insert into student values(104,'kavita','hyd',57.88);

1 row created.

SQL> select * from student;

SNO SNAME SADD AVG


---------- -------------------- -------------------- ----------
101 raja hyderbad 67.88
102 rajesh vizag 27.88
104 kavita hyd 57.88

step3) Develop Jdbc App (java app + jdbc code) to get records from "student" table
of oracle db s/w.
To get all records of "student" table, we need to use "SELECT * FROM
STUDENT" SQL Query which is SELECT
SQL Query..So use st.executeQuery(-) method to send and execute this SQL
Query in Db s/w.
package com.fg.jdbc;

public class SelectTest1 {


public static void main(String[] args)throws Exception {
//Load jdbc driver class (optional)
Class.forName("oracle.jdbc.driver.OracleDriver");

//Establish the connection with Oracle DB s/w


Connection
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","sco
tt","tiger");

//cretae JDBC Statement object


Statement statement=connection.createStatement();

//send and execute SQL SELECT Query in Db s/w


ResultSet rs=statement.executeQuery("SELECT * FROM STUDENT");

//process the ResultSet object


while(rs.next()!=false) {
System.out.println(rs.getInt(1)+"\t\t"+rs.getString(2)+"\t\
t"+rs.getString(3)+"\t\t"+rs.getFloat(4));
}
close jdbc objs
rs.close();
statement.close();
connection.close();
}//main
}//class

All jdbc objects like connection,statement,ResultSet are stream objects + network


socket objects which are
created having inter dependency ..So it is recommended to close them at the end of
the application in the
reverse order of their opening.
rs.close();
st.close();
con.close();
ResulSet object(rs) is closed means we can not do further processing on the
ResultSet Object.
Statement object(st) is closed means we can not use that statement object to send
and execute queries
in Db s/w further.
connection object(con)is closed means the connection/road between Java App and Db
s/w is closed.

Assignment1:Write a JDBC App to get records from DEPT table oracle db s/w?(default
db table of oracle).

write a jdbc app to insert record into student db table by collecting the values
from enduser.

package com.fg.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class InsertTest {
public static void main(String[] args) {
Scanner sc=null;
Connection con=null;
Statement st=null;

try {
//read input values
sc=new Scanner(System.in);
int no=0;
String name=null,addrs=null;
float avg=0.0f;
if(sc!=null) {
System.out.println("Enter student number ::");
no=sc.nextInt();//gives 1001
System.out.println("Enter student name ::");
name=sc.next();//gives raja
System.out.println("Enter student address");
addrs=sc.next();//gives hyd
System.out.println("Enter student avg ::");
avg=sc.nextFloat();//gives 90.6
}//if
//convert input values as required for the sql query
name="'"+name+"'";//gives 'raja'
addrs="'"+addrs+"'";//gives 'hyd'

//register JDBC driver software


Class.forName("oracle.jdbc.driver.OracleDriver");
//Establish connection

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","ti
ger");
//create Statement object
if(con!=null)
st=con.createStatement();
//prepare sql query
//insert into values(1001,'raja','hyd',90.6)
String query="INSERT INTO STUDENT
VALUES("+no+","+name+","+addrs+","+avg+")";
System.out.println(query);

//send and execute the sql query in Db s/w


if(st!=null) {
int count=st.executeUpdate(query);
//reprocess the process
if(count==0)
System.out.println("Record not inserted");
else
System.out.println("record inserted");
}//if
}//try
catch(SQLException se) {
se.printStackTrace();
}
catch(ClassNotFoundException cnf) {
cnf.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
//close jdbc objects
try {
if(st!=null)
st.close();
}
catch(SQLException se) {
se.printStackTrace();
}
try {
if(con!=null)
con.close();
}
catch(SQLException se) {
se.printStackTrace();
}
try {
if(sc!=null)
sc.close();
}
catch(Exception e) {
e.printStackTrace();
}
}//finally
}//main
}//class

Assignment2 :: write a jdbc app to insert record values into empno,ename,job,sal


column values of emp db table
of oracle Db s/w.(INERT INTO EMP(EMPNO,ENAME,SAL,JOB)VALUES(-,-,-,-);)

=>if u r getting connectivity issue with oracle Db s/w then make sure the following
two services of oracle
in running mode

write a JDBC App to update student addrs and avg based on the given student no?
package com.fg.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class UpdateTest {


public static void main(String[] args) {
Scanner sc=null;
Connection con=null;
Statement st=null;
try {
//read inputs
sc=new Scanner(System.in);
int no=0;
String newAddrs=null;
float newAvg=0.0f;
if(sc!=null) {
System.out.println("Enter student no to update his
details");
no=sc.nextInt();//gives 1001
System.out.println("Enter new addrs for student");
newAddrs=sc.next();//gives delhi
System.out.println("Enter new avg for student");
newAvg=sc.nextFloat();//gives 99.9
}
//convert input values as required for the sql query
newAddrs="'"+newAddrs+"'";//gives 'delhi'

//register JDBC driver s/w (optional)


Class.forName("oracle.jdbc.driver.OracleDriver");

//Establish the connection

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","ti
ger");

//create Statement object


if(con!=null)
st=con.createStatement();

//prepare sql query


//update student set sadd='vizag',avg=99.99 where sno=1001;
String query="UPDATE STUDENT SET
SADD="+newAddrs+",AVG="+newAvg+"WHERE SNO="+no;
System.out.println(query);

//send and execute the sql query


int count=0;
if(st!=null) {
count=st.executeUpdate(query);
}
//process the result
if(count==0) {
System.out.println("No record found for updation");
}
else {
System.out.println(count+"no.of records are updated");
}
}//try
catch(SQLException se) {
se.printStackTrace();
}
catch(ClassNotFoundException cnf) {
cnf.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
//close jdbc objects
try {
if(st!=null)
st.close();
}
catch(SQLException se) {
se.printStackTrace();
}
try {
if(con!=null)
con.close();
}
catch(SQLException se) {
se.printStackTrace();
}
try {
if(sc!=null)
sc.close();
}
catch(Exception e) {
e.printStackTrace();
}
}//finally
}//main
}//class

when we SQL Query to Db s/w from front end app like Java App , the Db s/w performs
3 operations on the SQL
Query
a)Parse/compile SQL Query
b)execute SQL Query
c)Fetch SQL Query result

1.Parse/compile
=>Here the received SQL Query will be splitted into multiple tokens(pieces)to
verify the syntax of SQL query
by compilation process.
select * from student

2.Execute
=>The parsed/compiled SQL Query will be executed to manupulate the DB tables data
or to get records from Db tables.

3.Fetch
=>The result/output of executed SQL Query will be collected/fetched and will be
given to Client app/front
end app.

3 types of Jdbc Statement objects:-


a)Simple Statement objects
(Implementation class object of java.sql.Statement(I))
b)PreparedStatement objects
(Implementation class objects of java.sql.PreparedStatement(I))
c)CallableStatement objects
(Implementation class object of java.sql.CallableStatement(I))

=>Simple Statement is not suitable for executing same sql query for multiple times
either with same input values
or with different input values.
=>In railways ticket reservation application, there will be need of executing same
insert sql query for
multiple times with different passenger details.
=>In Google search ,there will be need of executing same select query having the
same trending topic name as
the input value.
10,00,000 ticket booking in railway ticket reservation app for passengers(Using
Simple Statement object):
a)=>10,00,000 times same INSERT Query goes to Db s/w with
different input values :: 10,00,000 * 0.01 secs= 10,000 secs
b)=>10,00,000 times same INSERT Query will be
parsed/compiled in Db s/w for multiple times :: 10,00,000 * 0.01 secs=
10,000 secs
c)=>10,00,000 times same INSERT Query will be
executed in Db s/w for multiple times :: 10,00,000 * 0.01 secs= 10,000
secs
d)=>10,00,000 times same INSERT Query output will be
fetched out from Db s/w for multiple times :: 10,00,000 * 0.01 secs=
10,000
Performing (a),(b) operations on the same SQL Query for multiple times is really
unnecessary but perform
(c),(d) operations on the same multiple times is really required..But while working
simple statement object we
can send only raw SQL Query(query with input values) to Db s/w every time..So the
query has to go through
parse,execute, fetch operations every time.
what we want is performing (a),(b) operations only for 1 time with out input values
and performing(c),(d)
operations for multiple times with different sets input values...For this we need
to use PreparedStatement
objects that supports pre-compiled SQL Queries.

pre-compiled SQL Query:


=>The SQL Query that goes to Db s/w mostly with out input values and becomes
compiled/parsed Query irrespective
of wheather query will be executed or not is called pre-compiled Query.
=>JDBC PreparedStement object holds/represents the pre-compiled SQL Query and
allows to set input values,execute query and fetching the
results for multiple times i.e it is indirectly avoiding (a),(b) operations to
happen for multiple times but
allowing to happen(c),(d) operations for multiple times.

Limitations of Simple Statement object:


(a)Not suitable to execute same query for multiple either with same input values or
with different input values.
(b)Doex not allow to take parameters(?) in the SQL Query to set input values to
Query after compilation.
Note:Simple statement says i deal with raw/static SQL Queries i.e SQL Query must be
there with input values
in order to send and compile,execute in Db s/w.
=>INSERT INTO STUDENT VALUES(101,'raja','hyd',56.56)-static/Raw SQL Query
=>INSERT INTO STUDENT VALUES(?,?,?,?)-Dynamic SQL Query
(c)converting input values as required for the SQL Query ic very complex.
(d)There is a possibility of getting SQL Injection Problem.
(e)Supports to insert the Date Values to db table columns. but date values must be
given in the pattern that
supported by the underlying Db s/w i.e we can not give date values in our choice
pattern.
oracle date pattern :: dd-MMM-yy eg: 20-OCT-90
mysql date pattern :: yyyy-MM-dd eg: 1990-10-20
(f)Not suitable for inserting Large Object(LOBs)nothing but files
(g)Not the industry standard to use.
=>To slove all these problems take the support PreparedStatement object
PreparesStatement object:-
=>Represents or holds pre-compiled SQL Query
=>Allows to set values to parameters of pre-compiled SQL Query and also allows to
execute the same
pre-compiled SQL Query.
=>PreparedStatement object means it is the object of underlying JDBC driver s/w
supplied java class that
implements java.sql.PreparedStatement(I).

Procedure to work with PreparedStatement object:-


step1) create SQL Query having parameters(?)
String query="INSERT INTO STUDENT VALUES(?,?,?)"; (query parameters index
is 1 based)
(array index is 0 based)
step2)Make the SQL as pre-compiled SQL Query and hold/represent that Query using
PreparesStatement object.
Method calls
PreparedStatement ps=con.prepareStatement(query);
(interface) This method sends the SQL Query to Db s/w,make that
Query as pre-compiled SQL
Query and returns PreparedStatement obj having that pre-
compiled SQL Query
note:: Since PreparedStatement object represents pre-compiled SQL Query, so we
can use the same
PreparedStatement obj to set query param values, to execute the pre-compiled
Query and to gather results
of pre-compiled SQL Query.
step3)set values to the parameters(?) of pre-compiled SQL Query using
setXxx(-,-)methods
ps.setInt(1,1001);
ps.setString(2,"raja"); ps: pre-compiled SQL Query + input values(param
values)
ps.setString(3,"hyd");
ps.setFloat(4,67.88);
step4)execute the pre-compiled SQL Query
int result=ps.executeUpdate(); =>pre-compiled SQL Query goes to Db s/w
for execution and also gets
since "ps" obj itself holds the the query execution
results
pre-compiled SQL Query, so there is no need to passing SQL Query
separately to
executeUpdate() method.
step5)process the results
if(result==0)
System.out.println("record not inserted");
else
System.oyut.println("record inserted");
step6) Close jdbc objs
ps.close();
con.close();
note: To execute the "ps" represented pre-compiled SQL Query for multiple times
repeat setp3 to step5.

note::=>PreparedStatement obj can hold both SELECT or NON-SELECT pre-compiled SQL


Query
=>The pre-compiled SQL Query PreparedStatement obj can be the static sql
query or the dynamic sql query
//static sql query(query with out inputs or with hard coded inputs)
select * from student
select * from student where sno=101
insert into student values(1001,'rajesh','hyd',,67.88)

//dynamic sql query(query with dynamic inputs nothing but qyery with params)
select * from student where sno=?
insert into student values(?,?,?,?)
note: the pre-compiled SQL Query can be the static SQL Query or dynamic SQL Query.
=>Simple statement obj deals with only static SQL Queries
=>PreparedStatement obj deals with both static and dynamic SQL Queries as
pre-compiled SQL Queries.

=>Simple Statement object makes the Db s/w to compile the SQL Query just
before execution of the SQL
Query.(It is like current ticket booking)
=>PreparedStatement object makes Db s/w to compile the SQL Query irrespective
of wheather it will be
executed or not(It is like advanced ticket booking)

30-Apr-24
Write a JDBC app to insert "n" no.of student details in DB table.
=>To insert "n" student details collected from Enduser we need to execute the
INSERT SQL Query for "n"times..
For that JDBC PreparedStatement object is required to use.
package com.fg.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class PsInsertTest {


public static void main(String[] args) {
Scanner sc=null;
Connection con=null;
PreparedStatement ps=null;
try {
//read input
sc=new Scanner(System.in);
int count=0;
if(sc!=null) {
System.out.println("enter students count::");
count=sc.nextInt();
}
//register jdbc driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//Establish the connection

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","ti
ger");

//create preparedstatement object representing the pre-compiled


SQL Query
if(con!=null)
ps=con.prepareStatement("INSERT INTO STUDENT
VALUES(?,?,?,?)");
//read multiple student details and set them to pre-compiled
INSERT Query param values
for(int i=1;i<=count;++i) {
//read each student details
System.out.println("Enter"+i+"student details");
System.out.println("enter sno");
int sno=sc.nextInt();
System.out.println("enter sname");
String name=sc.next();
System.out.println("enter address");
String addrs=sc.next();
System.out.println("enter avg");
double avg=sc.nextDouble();
//set each student details to query param values
ps.setInt(1, sno);
ps.setString(2, name);
ps.setString(3, addrs);
ps.setDouble(4, avg);
//execute the SQl query
int result=ps.executeUpdate();
//process the results
if(result==0)
System.out.println(i+" record not inserted");
else
System.out.println(i+" record inserted");
}//for
}//try
catch(SQLException se) {
se.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
//close jdbc objects
try {
if(ps!=null)
ps.close();
}
catch(SQLException se) {
se.printStackTrace();
}
try {
if(con!=null)
con.close();
}
catch(SQLException se) {
se.printStackTrace();
}
try {
if(sc!=null)
sc.close();
}
catch(Exception e) {
e.printStackTrace();
}
}//finally
}//method
}//class
Assignment :: insert "n"no.of customer details to customer db table.

You might also like