Unit 1 - JDBC
Unit 1 - JDBC
UNIT 1: JDBC
1. Introduction
JDBC is a Set of java API'S [Application programming interface] which are used to
execute SQL Statement. JDBC stands for java database Connectivity. It Consist of
set of classes & interface return in java programming language.
It is developed by Sun microsystem. JDBC is an application programming interface
which provides mechanism for dynamically loading the correct java packages &
registering them with the JDBC driver manager. That is used as a connection
factory for Creating JDBC Connections which Supports Creating an executing
statements such as SQL insert, Update, &delete.
JDBC is an application programming interface that define how a java programmer
can access the database in tabular format from java code using a set of standard
interface & classes return in the java programming Language. JDBC provides
methods for querying & updating the data in relational database management
System such as SQL, Oracle, MySQL, etc.
JDBC is similar to open database connectivity [ODBC] which is used for accessing
& managing databases, but difference is that JDBC is design specifically for Java
programs whereas ODBC is not depended upon any language.
2. JDBC API
JDBC API provides programmatic access to relational data from the java
programming language using the JDBC APJ's, application can execute SQL
statement, retrieved result & propagate changes back to Underrating data source.
The Java JDBC API Can also interact with multiple data Source in a distributed
heterogeneous environment. The JDBC 2.0 API include two packages java.sql &
javax.sql known as JDBC standard extension. Together they contain the necessary
classes to develop database application using java.
1
Unit 1:JDBC
The JDBC API found in java.sql package. In simplest term a JDBC API make it
possible to three things.
A] Established a connection with a data source.
B] Send queries & update statements to the data source.
C] Process the result.
Method Description
Void close () Free & object of type Connection from database & other JDBC
resources.
Void commit () Makes all the changes since the last commit of roll back permanent
Statement create Create an object of type statement For Sending SQL statements to
statement() the database.
callable statements. It creates an object of type callable statement for calling the stored
prepare call (strings) procedures from database
Prepared statements It creates an object of type prepared statement for sending dynamic
prepare statements SQL statements to the database.
(string)
Boolean is closed () It returns true if the Connection is closed else return false.
Void rollback () The process of calling a function from another function is referred
to as rollback.
2
Unit 1:JDBC
5. JDBC Components
JDBC Consist of set of interfaces & classes which enables java programs to
execute SQL statements. Interfaces & classes in JDBC API are return in Java. The
JDBC API consist of following four Components.
Connection con=DriverManager.getConnection("URL,USER,PASS");
C] Statements - The JDBC statements are used to execute the SQL Or PLSQL
queries against the database. We need a statement for every single query. JDBC
API defines the Statement Callable Statement, Prepared statement types of
statement.
D] Result Sets - A query returns the data in the form of ResultSets. To read the
query result data ResultSet provides cursor that points to the Current row in the
ResultSet.
F] SQL Exception – This class handles any errors that occurred in a database
application.
3
Unit 1:JDBC
6. JDBC Driver
JDBC driver is a software Component that enables java applications to interact with
the database "There are 4 types of JDBC drivers.
Advantages
I) Easy to use
II) It can be easily connected to any database
Disadvantage
I) Performance degraded because JDBC method Call is Converted into ODBC
function call
II) The ODBC driver needs to be installed on the client machine.
4
Unit 1:JDBC
Note - In Java 8 JDBC - ODBC - Bridge has been removed. Oracle doesn't support
the JDBC - ODBC Bridge from Java 8. Oracle recommends that you used JDBC
drivers provided by the vender of your database instead of the JDBC-ODBC bridge.
Advantage
I) Performance Upgraded than JOBC-ODAC-BRIDGE Driver
Disadvantage
I) The native driver needs to be installed on each client machine.
II) The vender client library needs to be installed on client machine.
Advantage
I) No client-side library is required because of application served that can perform
many tasks like load balancing, logging, etc.
Disadvantage
I) Network Support is required on client-machine.
II) Requires database Specific coding to be done in the middle time.
III) Maintenance of network Protocol driver becomes Costly because it requires
database Specific Coding to be done in the middle timer.
D] Thin Driver –
The thin Driver Converts JDBC calls directly into Vendors Specific database protocol.
That is why it is known as Thin Driver. It is fully return in Java language. It is most
frequently use JDBC driver type.
6
Unit 1:JDBC
Advantage
I) Better performance than all other drivers.
II) No Software is required at client side or Server side.
Disadvantage
I) Drivers depends on the database.
There are 5 Steps to Connect any java application with the database using JDBC. The
Steps are as follows:
Syntax:
7
Unit 1:JDBC
B] Create Connection –
The getConnection() of Driver Manager class is used to establish a Connection with
the database
Syntax:
public static Connection get connection (string URL)throws SQL Exception.
Connection con=DriverManager.getConnection("");
("jdbc:mysql://localhost:3306/b56","root","root");
C] Create statement –
This method createStatement() of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
Syntax:
public statement create statement () throws SQL Exception.
It is responsible to Use the query in database
Statement stmt=con.createStatement();
D] Execute queries –
executeQuery() of statement interface is used to execute queries with database. This
method returns the object of ResultSet that can be used to get all the records of the
table.
Syntax:
public ResultSet executeQuery (string SQL) throws SQLException
ResultSet rs = stmt.executeQuery(“select count(tno) from teacher”);
while(rs.next()) {
System.out.println(rs.getInt(1));
}
E] Close Connection –
8
Unit 1:JDBC
By closing connection object statement & result set will be close automatically. The
close() of connection interface is used to close the connection.
Syntax:
Public void close()throws SQLException
con.close();
8. Architecture of JDBC
JDBC API is divided into user level API for processing SQL statements & handling
all applications to JDBC driver manager Communication & a JDBC driver API that
database venders use to interface their database drivers to java gives us an overview
of the JDBC architecture.
The JDBC driver managed is the core of the JDBC architecture & Serve to Connect
the java application with one of the four different driver types.
The classes that you use for JDBC programming are Contain in the java.sql &
javax.sql Package. The JDBC architecture Can be classified into two categories
A] JDBC API
B] Types of JDBC drivers
[For more info see point no 5 & 6]
2-tier model java applet or application interface direct with database. A JDBC
driver is required to communicate with the particular DBMS which is being
access. The SQL statements are sent to the database & used gets the result.
9
Unit 1:JDBC
3-tier model in the 3-tier model commands are send to a middle tier of Services
which then sends the Commands to the data Source. The data Source process the
Commands & Send to the result Back to the middle tier which then sends them
to the user.
10
Unit 1:JDBC
MIS directors find the 3-tier model very attractive because the middle tier makes
it possible to maintain control over access & the kinds of updates that can be
made to the corporate data. Another advantage is that it simplifies the
deployment of the application. Finally, in many cases 3-tier architecture can
provide performance.
12
Unit 1:JDBC
All parameters in JDBC are presented by ? mark Symbol which known as parameter
marker you must supply values For every parameter before executing SQL statement. It
improves performance of application will be faster if you are use prepared statement
interface because is compiled only once.
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter
value) index.
public void setString(int paramIndex, sets the String value to the given parameter
String value) index.
public void setFloat(int paramIndex, float sets the float value to the given parameter
value) index.
public void setDouble(int paramIndex, sets the double value to the given parameter
double value) index.
public int executeUpdate() executes the query. It is used for create,
drop, insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an
instance of ResultSet.
13
Unit 1:JDBC
14
Unit 1:JDBC
12. Programs
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
public class Employee {
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
System.out.println("\n");
System.out.println("\t" +rs.getInt(1));
System.out.println("\t" +rs.getString(2));
System.out.println("\t" +rs.getString(3));
System.out.println("\t" +rs.getInt(4));
}
}
catch(Exception e) {
System.out.print(e);
}
}
}
15
Unit 1:JDBC
2. Write a java program to create Teacher table(TNo.TName, Sal, Desg) and insert a
record in it.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Teacher {
16
Unit 1:JDBC
3. Write a JDBC program to delete the records of employees whose names are starts
with 'a' character
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Delete {
17
Unit 1:JDBC
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Count {
18
Unit 1:JDBC
package javaprograms;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
19
Unit 1:JDBC
6. Write a JDBC program to accept the details of customer (CID, CName, Address,
Ph_No) and store it into the database (Use Prepared Statement interface)
import java.util.Scanner;
import java.sql.*;
public class Custtable {
public static void main(String[] args) {
// TODO Auto-generated method stub
PreparedStatement ps;
try
{
int cid,no;
String cname,caddr,pno;
Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/b56","root","root");
if(con==null)
{
/ System.out.print("Connection Failed");
}
String sql="insert into Customer1 values(?,?,?,?)";
ps=con.prepareStatement(sql);
System.out.println("Customer Details....");
System.out.println("Enter Cid");
cid=sc.nextInt();
ps.setInt(1, cid);
System.out.println("Enter Cname");
cname=sc.nextLine();
ps.setString(2, cname);
System.out.println("Enter Pno");
pno=sc.nextLine();
ps.setString(3, pno);
System.out.println("Enter Caddr");
caddr=sc.nextLine();
20
Unit 1:JDBC
ps.setString(4, caddr);
no=ps.executeUpdate();
if(no!=0)
System.out.println("Record added successfully");
else
System.out.println("Record Not added");
con.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
21
Unit 1:JDBC
package javaprograms;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
22
Unit 1:JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
public class mobile {
}catch(Exception e)
{
System.out.println(e);
}
}
}
24
Unit 1:JDBC
9. Write a JDBC Program in java to display the names of Employees starting with
'S' character.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class empstarts {
System.out.println("\n"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+
rs.getInt(4));
}
}
catch(Exception e)
{
System.out.println(e);
}
}
25
Unit 1:JDBC
10. Write a JDBC program to delete the details of given employee (ENoEName
Salary).
package javaprograms;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
26
Unit 1:JDBC
11. Write a java program to create a student table with field’s rno, name and per.
Insert values in the table. Display all the details of the student on screen. (Use
PreparedStatement Interface).
import java.sql.*;
import java.util.Scanner;
public class student {
no=ps.executeUpdate();
if(no!=0)
System.out.println("Data inserted succesfully.....");
else
System.out.println("Data not inserted");
ResultSet rs=stmt.executeQuery("select * from
Student1");
System.out.println("rno\t"+"sname\t"+"perc");
while(rs.next())
{
System.out.println("\n"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}