SlideShare une entreprise Scribd logo
1  sur  81
JDBC(Java Database
Connectivity)
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Java JDBC is a java API to connect and execute query
with the database. JDBC API uses jdbc drivers to connect
with the database
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Why use JDBC
 Before JDBC, ODBC API was the database API to
connect and execute query with the database. But,
ODBC API uses ODBC driver which is written in C
language (i.e. platform dependent and unsecured). That is
why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
BY LECTURER SURAJ PANDEY CCT
COLLEGE
What is API
 API (Application programming interface) is a document
that contains description of all the features of a product
or software. It represents classes and interfaces that
software programs can follow to communicate with each
other. An API can be created for applications, libraries,
operating systems, etc
BY LECTURER SURAJ PANDEY CCT
COLLEGE
JDBC Driver
 JDBC Driver is a software component that enables java
application to interact with the database.There are 4
types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
BY LECTURER SURAJ PANDEY CCT
COLLEGE
1) 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 the ODBC function
calls. This is now discouraged because of thin driver.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Advantages:
 easy to use.
 can be easily connected to any database.
Disadvantages:
 Performance degraded because JDBC method call is
converted into the ODBC function calls.
 The ODBC driver needs to be installed on the client
machine.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
2) Native-API driver
 The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely
in java.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Advantage:
 performance upgraded than JDBC-ODBC bridge driver.
 Disadvantage:
 The Native driver needs to be installed on the each client
machine.
 The Vendor client library needs to be installed on client
machine.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
3) Network Protocol driver
 The Network Protocol driver uses middleware
(application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is
fully written in java.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Advantage:
 No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
 Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the
middle tier.
 Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in
the middle tier.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
4) Thin driver
 The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.
 Disadvantage:
 Drivers depends on the Database.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
JDBC Architecture
 Two-tier and Three-tier Processing Models
 The JDBC API supports both two-tier and three-tier
processing models for database access.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 In the two-tier model, a Java applet or application talks
directly to the data source. This requires a JDBC driver
that can communicate with the particular data source
being accessed. A user's commands are delivered to the
database or other data source, and the results of those
statements are sent back to the user. The data source
may be located on another machine to which the user is
connected via a network. This is referred to as a
client/server configuration, with the user's machine as the
client, and the machine housing the data source as the
server. The network can be an intranet, which, for
example, connects employees within a corporation, or it
can be the Internet.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
three-tier model
 In the three-tier model, commands are sent to a "middle
tier" of services, which then sends the commands to the
data source. The data source processes the commands
and sends the results back to the middle tier, which then
sends them to the user. MIS directors find the three-tier
model very attractive because the middle tier makes it
possible to maintain control over access and the kinds of
updates that can be made to corporate data. Another
advantage is that it simplifies the deployment of
applications. Finally, in many cases, the three-tier
architecture can provide performance advantages.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
5 Steps to connect to the database in java
There are 5 steps to connect any java application with the
database in java using JDBC. They are as follows:
1. Register the driver class
2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object
BY LECTURER SURAJ PANDEY CCT
COLLEGE
1) Register the driver class
 The forName() method of Class class is used to register
the driver class. This method is used to dynamically load
the driver class.
 Syntax of forName() method
1.public static void forName(String className)throws 
ClassNotFoundException  
 Example to register the OracleDriver class
1. Class.forName("oracle.jdbc.driver.OracleDriver");  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 2) Create the connection object
 The getConnection() method of DriverManager class is
used to establish connection with the database.
 Syntax of getConnection() method
 1) public static Connection getConnection(String url)th
rows SQLException  
 2) public static Connection getConnection(String url,St
ring name,String password)  
throws SQLException  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example to establish connection with the Oracle
database
1. Connection con=DriverManager.getConnection(  "jdbc:o
racle:thin:@localhost:1521:xe","system","password");  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 3) Create the Statement object
The createStatement() method of Connection interface is
used to create statement. The object of statement is
responsible to execute queries with the database.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Syntax of createStatement() method
 public Statement createStatement()throws SQLExcepti
on  
 Example to create the statement object
 Statement stmt=con.createStatement();  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 4) Execute the query
 The executeQuery() method of Statement interface is
used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all
the records of a table.
 Syntax of executeQuery() method
 public ResultSet executeQuery(String sql)throws SQLE
xception  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");    
while(rs.next()){  
System.out.println(rs.getInt(1)+" "+rs.getString(2));  
}  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 5) Close the connection object
 By closing connection object statement and ResultSet will
be closed automatically. The close() method of
Connection interface is used to close the connection.
 Syntax of close() method
 public void close()throws SQLException  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example to close connection
 con.close();  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example to connect to the Oracle database
 For connecting java application with the oracle database,
you need to follow 5 steps to perform database
connectivity.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G
database is jdbc:oracle:thin:@localhost:1521:xewhere
jdbc is the API, oracle is the database, thin is the driver,
localhost is the server name on which oracle is running, we
may also use IP address, 1521 is the port number and XE is
the Oracle service name. You may get all these informations
from the tnsnames.ora file.
3. Username: The default username for the oracle database
is system.
4. Password: Password is given by the user at the time of
installing the oracle database
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 To connect Netbeans IDE to Oracle 10g Express
Edition . You need to do Following steps:
 Install Oracle 10g Express Edition
 Create the main user as :system, and password can be
anything you want.
 After that open Sql Command Line and type the
following codes:
 Connect system/yourpassword; and then press enter
 Than type the following code
 Create user myuse identified by mypassword; press enter
 Grant connect,resource to myuse; press enter
 Now connect with the user that you just created.
 Connect myuse/mypassword; press enter;
 Now create a simple Table For testing Purposes, here is
the code
 Create table Testing( no number primary key, name
varchar2(20));
 Now Insert some values
 Insert into Testing values(1,’Ravi’);
 Now press this word
 Commit; and than press enter
 Now download the ojdbc7.jar driver from internet which
is compatible with netbeans.
 Open Netbeans IDE
 Let's first create a table in oracle database.
 create table myuse(id number(10),name varchar2(40)); 
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 import java.sql.*;
 public class ConnectOracle {
 public static void main(String[] args) throws ClassNotFoundException {
 // TODO code application logic here
 Connection conn=null;
 try
 {
 String driverName="oracle.jdbc.driver.OracleDriver";
 Class.forName(driverName);
 String serverName="localhost";
 String serverPort="1521";
 String sid="XE";
 String url="jdbc:oracle:thin:@"+serverName+":"+serverPort+":"+sid;
 String username="myuse";
 String password="mypassword";
 conn=DriverManager.getConnection(url,username,password);
 System.out.println("Successfully connected to the database");
 }
 catch(ClassNotFoundException e)BY LECTURER SURAJ PANDEY CCT
COLLEGE
 {
 System.out.println("could not find the database driver"+e.getMessage());
 }
 catch(SQLException e)
 {
 System.out.println("Could not connect to the database"+e.getMessage());
 }
 try
 {
 Statement st=conn.createStatement();
 ResultSet rs=st.executeQuery("select * from Testing");
 while(rs.next())
 {
 int no=rs.getInt(1);
 String name=rs.getString(2).toString();
 System.out.println(""+no+""+name);
 }
 rs.close();

BY LECTURER SURAJ PANDEY CCT
COLLEGE
 }
 catch(Exception e)
 {
 e.printStackTrace();
 }
 }

 }
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 To connect java application with the Oracle database
ojdbc14.jar file is required to be loaded.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example to connect to the mysql database
 For connecting java application with the mysql database,
you need to follow 5 steps to perform database
connectivity.
 In this example we are using MySql as the database. So
we need to know following informations for the mysql
database:
BY LECTURER SURAJ PANDEY CCT
COLLEGE
1. Driver class: The driver class for the mysql database
is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql
database is jdbc:mysql://localhost:3306/sonoo where
jdbc is the API, mysql is the database, localhost is the server
name on which mysql is running, we may also use IP
address, 3306 is the port number and sonoo is the database
name. We may use any database, in such case, you need to
replace the sonoo with your database name.
3. Username: The default username for the mysql database
is root.
4. Password: Password is given by the user at the time of
installing the mysql database. In this example, we are going
to use root as the password.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Let's first create a table in the mysql database, but before
creating table, we need to create database first.
1. create database sonoo;  
2. use sonoo;  
3. create table emp(id int(10),name varchar(40),age int(3)); 
 
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example to Connect Java Application with
mysql database
 In this example, sonoo is the database name, root is the
username and password.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 import java.sql.*;  
class MysqlCon{  
public static void main(String args[]){  
try{  
Class.forName("com.mysql.jdbc.Driver");   
Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost:3306/sonoo","root","root");    
//here sonoo is database name, root is username and password  
Statement stmt=con.createStatement();    
ResultSet rs=stmt.executeQuery("select * from emp");    
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
  
con.close();    
}catch(Exception e){ System.out.println(e);}   
}  
}  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 The above example will fetch all the records of emp
table.
 To connect java application with the mysql database
mysqlconnector.jar file is required to be loaded.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
DriverManager class:
 The DriverManager class acts as an interface between
user and drivers. It keeps track of the drivers that are
available and handles establishing a connection between a
database and the appropriate driver. The DriverManager
class maintains a list of Driver classes that have registered
themselves by calling the method
DriverManager.registerDriver().
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Connection interface:
 A Connection is the session between java application and
database. The Connection interface is a factory of
Statement, PreparedStatement, and DatabaseMetaData
i.e. object of Connection can be used to get the object of
Statement and DatabaseMetaData. The Connection
interface provide many methods for transaction
management like commit(),rollback() etc.
 By default, connection commits the changes after
executing queries.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement object 
that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Commonly used methods of Connection interface:
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Statement interface
 The Statement interface provides methods to execute queries
with the database. The statement interface is a factory of ResultSet
i.e. it provides factory method to get the object of ResultSet.
 Commonly used methods of Statement interface:
 The important methods of Statement interface are as follows:
 1) public ResultSet executeQuery(String sql): is used to
execute SELECT query. It returns the object of ResultSet.
 2) public int executeUpdate(String sql): is used to execute
specified query, it may be create, drop, insert, update, delete etc.
 3) public boolean execute(String sql): is used to execute
queries that may return multiple results.
 4) public int[] executeBatch(): is used to execute batch of
commands.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Example of Statement interface
 Let’s see the simple example of Statement interface to
insert, update and delete the record.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 import java.sql.*;  
class FetchRecord{  
public static void main(String args[])throws Exception{    
Class.forName("oracle.jdbc.driver.OracleDriver");  
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe","system","oracle");  
Statement stmt=con.createStatement();    
//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");  
//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=
10000 where id=33");  
int result=stmt.executeUpdate("delete from emp765 where id=33");    
System.out.println(result+" records affected");  
con.close();  
}}  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
PreparedStatement interface
 The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
 Let's see the example of parameterized query:
 String sql="insert into emp values(?,?,?)";  
 As you can see, we are passing parameter (?) for the
values. Its value will be set by calling the setter methods
of PreparedStatement.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Why use PreparedStatement?
 Improves performance: The performance of the
application will be faster if you use PreparedStatement
interface because query is compiled only once.
 How to get the instance of PreparedStatement?
 The prepareStatement() method of Connection interface
is used to return the object of PreparedStatement.
Syntax:
 public PreparedStatement prepareStatement(String quer
y)throws SQLException{} 
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Methods of PreparedStatement interface
 The important methods of PreparedStatement interface
are given below:
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of PreparedStatement interface that inserts the
record
 First of all create table as given below:
 create table emp(id number(10),name varchar2(50));  
 Now insert records in this table by the code given below:
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 import java.sql.*;  
 class InsertPrepared{  
 public static void main(String args[]){  
 try{  
 Class.forName("oracle.jdbc.driver.OracleDriver");  
 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@loc
alhost:1521:xe","system","oracle");    
 PreparedStatement stmt=con.prepareStatement("insert into Emp value
s(?,?)");  
 stmt.setInt(1,101);//1 specifies the first parameter in the query  
 stmt.setString(2,"Ratan");  
 int i=stmt.executeUpdate();  
 System.out.println(i+" records inserted");  
 con.close();  
 }catch(Exception e){ System.out.println(e);}  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of PreparedStatement interface that updates the
record
 PreparedStatement stmt=con.prepareStatement("update 
emp set name=? where id=?");  
 stmt.setString(1,"Sonoo");//1 specifies the first parameter 
in the query i.e. name  
 stmt.setInt(2,101);  
   
 int i=stmt.executeUpdate();  
 System.out.println(i+" records updated");  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of PreparedStatement interface that deletes the
record
 PreparedStatement stmt=con.prepareStatement("delete f
rom emp where id=?");  
 stmt.setInt(1,101);  
   
 int i=stmt.executeUpdate();  
 System.out.println(i+" records deleted");  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of PreparedStatement interface that retrieve the
records of a table
 PreparedStatement stmt=con.prepareStatement("select * 
from emp");  
 ResultSet rs=stmt.executeQuery();  
 while(rs.next()){  
 System.out.println(rs.getInt(1)+" "+rs.getString(2));  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of PreparedStatement to insert records until
user press n
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 import java.sql.*;  
 import java.io.*;  
 class RS{  
 public static void main(String args[])throws Exception{  
 Class.forName("oracle.jdbc.driver.OracleDriver");  
 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:xe","system","oracle");  
 PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");  
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
 do{  
 System.out.println("enter id:");  
 int id=Integer.parseInt(br.readLine());  
 System.out.println("enter name:");  
 String name=br.readLine();  
 System.out.println("enter salary:");  
 float salary=Float.parseFloat(br.readLine());  
 ps.setInt(1,id);  
 ps.setString(2,name);  
 ps.setFloat(3,salary);  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 int i=ps.executeUpdate();  
 System.out.println(i+" records affected");  
 System.out.println("Do you want to continue: y/n");  
 String s=br.readLine();  
 if(s.startsWith("n")){  
 break;  
 }  
 }while(true);  
 con.close();  
 }}  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
CallableStatement Interface
 To call the stored procedures and functions,
CallableStatement interface is used.
 We can have business logic on the database by the use of
stored procedures and functions that will make the
performance better because these are precompiled.
 Suppose you need the get the age of the employee based
on the date of birth, you may create a function that
receives date as the input and returns age of the
employee as the output.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
How to get the instance of CallableStatement?
 The prepareCall() method of Connection interface
returns the instance of CallableStatement. Syntax is given
below:
 public CallableStatement prepareCall("{ call procedurena
me(?,?...?)}");  
 The example to get the instance of CallableStatement is
given below:
 CallableStatement stmt=con.prepareCall("{call myproced
ure(?,?)}");  
 It calls the procedure myprocedure that receives 2
arguments.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
ResultSet interface
 The object of ResultSet maintains a cursor pointing to a
particular row of data. Initially, cursor points to before the
first row.
 By default, ResultSet object can be moved forward
only and it is not updatable.
 But we can make this object to move forward and backward
direction by passing either TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
 Statement stmt = con.createStatement(ResultSet.TYPE_SCRO
LL_INSENSITIVE,  
                      ResultSet.CONCUR_UPDATABLE);  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Commonly used methods of ResultSet interface
BY LECTURER SURAJ PANDEY CCT
COLLEGE
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Example of Scrollable ResultSet
 Let’s see the simple example of ResultSet interface to
retrieve the data of 3rd row.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 import java.sql.*;  
 class FetchRecord{  
 public static void main(String args[])throws Exception{    
 Class.forName("oracle.jdbc.driver.OracleDriver");  
 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe","system","oracle");  
 Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIV
E,ResultSet.CONCUR_UPDATABLE);  
 ResultSet rs=stmt.executeQuery("select * from emp765");  
 //getting the record of 3rd row  
 rs.absolute(3);  
 System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));  
 con.close();  
 }}  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
ResultSetMetaData Interface
 The metadata means data about data i.e. we can get
further information from the data.
 If you have to get metadata of a table like total number of
column, column name, column type etc. ,
ResultSetMetaData interface is useful because it provides
methods to get metadata from the ResultSet object.
BY LECTURER SURAJ PANDEY CCT
COLLEGE
Commonly used methods of ResultSetMetaData interface
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 How to get the object of ResultSetMetaData:
 The getMetaData() method of ResultSet interface returns
the object of ResultSetMetaData. Syntax:
 public ResultSetMetaData getMetaData()throws SQLEx
ception  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 import java.sql.*;  
 class Rsmd{  
 public static void main(String args[]){  
 try{  
 Class.forName("oracle.jdbc.driver.OracleDriver");    
 Connection con=DriverManager.getConnection(  
 "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
 PreparedStatement ps=con.prepareStatement("select * from emp");  
 ResultSet rs=ps.executeQuery();  
 ResultSetMetaData rsmd=rs.getMetaData();  
 System.out.println("Total columns: "+rsmd.getColumnCount());  
 System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));  
 System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));  
 con.close();  
 }catch(Exception e){ System.out.println(e);}  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT
COLLEGE
 Output:Total columns: 2
 Column Name of 1st column: ID
 Column Type Name of 1st column: NUMBER
BY LECTURER SURAJ PANDEY CCT
COLLEGE

Contenu connexe

Tendances

Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java Hitesh-Java
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Strings in Java
Strings in Java Strings in Java
Strings in Java Hitesh-Java
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for DesignersR. Sosa
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 

Tendances (20)

Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
OOP java
OOP javaOOP java
OOP java
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
JDBC
JDBCJDBC
JDBC
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 

Similaire à Basic Java Database Connectivity(JDBC)

JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity DevAdnani
 
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptxujjwalmatoliya
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2msafad
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Airline report
Airline reportAirline report
Airline reportSimranBani
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptkingkolju
 

Similaire à Basic Java Database Connectivity(JDBC) (20)

Jdbc
JdbcJdbc
Jdbc
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
 
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc
jdbcjdbc
jdbc
 
Jdbc new
Jdbc newJdbc new
Jdbc new
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Airline report
Airline reportAirline report
Airline report
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
 

Plus de suraj pandey

Systemcare in computer
Systemcare in computer Systemcare in computer
Systemcare in computer suraj pandey
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructorsuraj pandey
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.netsuraj pandey
 
Basic in Computernetwork
Basic in ComputernetworkBasic in Computernetwork
Basic in Computernetworksuraj pandey
 
History of computer
History of computerHistory of computer
History of computersuraj pandey
 
Basic of Internet&email
Basic of Internet&emailBasic of Internet&email
Basic of Internet&emailsuraj pandey
 
Basic fundamental Computer input/output Accessories
Basic fundamental Computer input/output AccessoriesBasic fundamental Computer input/output Accessories
Basic fundamental Computer input/output Accessoriessuraj pandey
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.netsuraj pandey
 
Transmission mediums in computer networks
Transmission mediums in computer networksTransmission mediums in computer networks
Transmission mediums in computer networkssuraj pandey
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.netsuraj pandey
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computersuraj pandey
 
Computer Fundamental Network topologies
Computer Fundamental Network topologiesComputer Fundamental Network topologies
Computer Fundamental Network topologiessuraj pandey
 
Basic of Computer software
Basic of Computer softwareBasic of Computer software
Basic of Computer softwaresuraj pandey
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Javasuraj pandey
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Javasuraj pandey
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVAsuraj pandey
 

Plus de suraj pandey (20)

Systemcare in computer
Systemcare in computer Systemcare in computer
Systemcare in computer
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Basic in Computernetwork
Basic in ComputernetworkBasic in Computernetwork
Basic in Computernetwork
 
Computer hardware
Computer hardwareComputer hardware
Computer hardware
 
Dos commands new
Dos commands new Dos commands new
Dos commands new
 
History of computer
History of computerHistory of computer
History of computer
 
Dos commands
Dos commandsDos commands
Dos commands
 
Basic of Internet&email
Basic of Internet&emailBasic of Internet&email
Basic of Internet&email
 
Basic fundamental Computer input/output Accessories
Basic fundamental Computer input/output AccessoriesBasic fundamental Computer input/output Accessories
Basic fundamental Computer input/output Accessories
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
 
Transmission mediums in computer networks
Transmission mediums in computer networksTransmission mediums in computer networks
Transmission mediums in computer networks
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.net
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computer
 
Computer Fundamental Network topologies
Computer Fundamental Network topologiesComputer Fundamental Network topologies
Computer Fundamental Network topologies
 
Basic of Computer software
Basic of Computer softwareBasic of Computer software
Basic of Computer software
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Java
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVA
 
Generics in java
Generics in javaGenerics in java
Generics in java
 

Dernier

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Dernier (20)

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Basic Java Database Connectivity(JDBC)

  • 2.  Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 3. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 4. Why use JDBC  Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language). BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 5. What is API  API (Application programming interface) is a document that contains description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other. An API can be created for applications, libraries, operating systems, etc BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 6. JDBC Driver  JDBC Driver is a software component that enables java application to interact with the database.There are 4 types of JDBC drivers: 1. JDBC-ODBC bridge driver 2. Native-API driver (partially java driver) 3. Network Protocol driver (fully java driver) 4. Thin driver (fully java driver) BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 7. 1) 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 the ODBC function calls. This is now discouraged because of thin driver. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 8. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 9. Advantages:  easy to use.  can be easily connected to any database. Disadvantages:  Performance degraded because JDBC method call is converted into the ODBC function calls.  The ODBC driver needs to be installed on the client machine. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 10. 2) Native-API driver  The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 11. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 12.  Advantage:  performance upgraded than JDBC-ODBC bridge driver.  Disadvantage:  The Native driver needs to be installed on the each client machine.  The Vendor client library needs to be installed on client machine. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 13. 3) Network Protocol driver  The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 14. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 15.  Advantage:  No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.  Disadvantages:  Network support is required on client machine.  Requires database-specific coding to be done in the middle tier.  Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 16. 4) Thin driver  The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 17. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 18.  Advantage:  Better performance than all other drivers.  No software is required at client side or server side.  Disadvantage:  Drivers depends on the Database. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 19. JDBC Architecture  Two-tier and Three-tier Processing Models  The JDBC API supports both two-tier and three-tier processing models for database access. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 20. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 21.  In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 22. three-tier model  In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 23. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 24. 5 Steps to connect to the database in java There are 5 steps to connect any java application with the database in java using JDBC. They are as follows: 1. Register the driver class 2. Create the connection object 3. Create the Statement object 4. Execute the query 5. Close the connection object BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 25. 1) Register the driver class  The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.  Syntax of forName() method 1.public static void forName(String className)throws  ClassNotFoundException    Example to register the OracleDriver class 1. Class.forName("oracle.jdbc.driver.OracleDriver");   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 26.  2) Create the connection object  The getConnection() method of DriverManager class is used to establish connection with the database.  Syntax of getConnection() method  1) public static Connection getConnection(String url)th rows SQLException    2) public static Connection getConnection(String url,St ring name,String password)   throws SQLException   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 27.  Example to establish connection with the Oracle database 1. Connection con=DriverManager.getConnection(  "jdbc:o racle:thin:@localhost:1521:xe","system","password");   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 28.  3) Create the Statement object The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 29.  Syntax of createStatement() method  public Statement createStatement()throws SQLExcepti on    Example to create the statement object  Statement stmt=con.createStatement();   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 30.  4) Execute the query  The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.  Syntax of executeQuery() method  public ResultSet executeQuery(String sql)throws SQLE xception   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 31. Example to execute query ResultSet rs=stmt.executeQuery("select * from emp");     while(rs.next()){   System.out.println(rs.getInt(1)+" "+rs.getString(2));   }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 32.  5) Close the connection object  By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.  Syntax of close() method  public void close()throws SQLException   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 33. Example to close connection  con.close();   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 34. Example to connect to the Oracle database  For connecting java application with the oracle database, you need to follow 5 steps to perform database connectivity. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 35. 1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver. 2. Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xewhere jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. You may get all these informations from the tnsnames.ora file. 3. Username: The default username for the oracle database is system. 4. Password: Password is given by the user at the time of installing the oracle database BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 36.  To connect Netbeans IDE to Oracle 10g Express Edition . You need to do Following steps:  Install Oracle 10g Express Edition  Create the main user as :system, and password can be anything you want.  After that open Sql Command Line and type the following codes:
  • 37.  Connect system/yourpassword; and then press enter  Than type the following code  Create user myuse identified by mypassword; press enter  Grant connect,resource to myuse; press enter  Now connect with the user that you just created.  Connect myuse/mypassword; press enter;  Now create a simple Table For testing Purposes, here is the code
  • 38.  Create table Testing( no number primary key, name varchar2(20));  Now Insert some values  Insert into Testing values(1,’Ravi’);  Now press this word  Commit; and than press enter
  • 39.  Now download the ojdbc7.jar driver from internet which is compatible with netbeans.  Open Netbeans IDE
  • 40.  Let's first create a table in oracle database.  create table myuse(id number(10),name varchar2(40));  BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 41.  import java.sql.*;  public class ConnectOracle {  public static void main(String[] args) throws ClassNotFoundException {  // TODO code application logic here  Connection conn=null;  try  {  String driverName="oracle.jdbc.driver.OracleDriver";  Class.forName(driverName);  String serverName="localhost";  String serverPort="1521";  String sid="XE";  String url="jdbc:oracle:thin:@"+serverName+":"+serverPort+":"+sid;  String username="myuse";  String password="mypassword";  conn=DriverManager.getConnection(url,username,password);  System.out.println("Successfully connected to the database");  }  catch(ClassNotFoundException e)BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 42.  {  System.out.println("could not find the database driver"+e.getMessage());  }  catch(SQLException e)  {  System.out.println("Could not connect to the database"+e.getMessage());  }  try  {  Statement st=conn.createStatement();  ResultSet rs=st.executeQuery("select * from Testing");  while(rs.next())  {  int no=rs.getInt(1);  String name=rs.getString(2).toString();  System.out.println(""+no+""+name);  }  rs.close();  BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 43.  }  catch(Exception e)  {  e.printStackTrace();  }  }   } BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 44.  To connect java application with the Oracle database ojdbc14.jar file is required to be loaded. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 45. Example to connect to the mysql database  For connecting java application with the mysql database, you need to follow 5 steps to perform database connectivity.  In this example we are using MySql as the database. So we need to know following informations for the mysql database: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 46. 1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver. 2. Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name. We may use any database, in such case, you need to replace the sonoo with your database name. 3. Username: The default username for the mysql database is root. 4. Password: Password is given by the user at the time of installing the mysql database. In this example, we are going to use root as the password. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 47.  Let's first create a table in the mysql database, but before creating table, we need to create database first. 1. create database sonoo;   2. use sonoo;   3. create table emp(id int(10),name varchar(40),age int(3));    BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 48. Example to Connect Java Application with mysql database  In this example, sonoo is the database name, root is the username and password. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 50.  The above example will fetch all the records of emp table.  To connect java application with the mysql database mysqlconnector.jar file is required to be loaded. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 51. DriverManager class:  The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver(). BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 52. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 53. Connection interface:  A Connection is the session between java application and database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit(),rollback() etc.  By default, connection commits the changes after executing queries. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 54. 1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries. 2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement object  that will generate ResultSet objects with the given type and concurrency. 3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true. 4) public void commit(): saves the changes made since the previous commit/rollback permanent. 5) public void rollback(): Drops all changes made since the previous commit/rollback. 6) public void close(): closes the connection and Releases a JDBC resources immediately. Commonly used methods of Connection interface: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 55. Statement interface  The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.  Commonly used methods of Statement interface:  The important methods of Statement interface are as follows:  1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.  2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.  3) public boolean execute(String sql): is used to execute queries that may return multiple results.  4) public int[] executeBatch(): is used to execute batch of commands. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 56. Example of Statement interface  Let’s see the simple example of Statement interface to insert, update and delete the record. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 58. PreparedStatement interface  The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.  Let's see the example of parameterized query:  String sql="insert into emp values(?,?,?)";    As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 59. Why use PreparedStatement?  Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.  How to get the instance of PreparedStatement?  The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax:  public PreparedStatement prepareStatement(String quer y)throws SQLException{}  BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 60. Methods of PreparedStatement interface  The important methods of PreparedStatement interface are given below: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 61. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 62.  Example of PreparedStatement interface that inserts the record  First of all create table as given below:  create table emp(id number(10),name varchar2(50));    Now insert records in this table by the code given below: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 63.  import java.sql.*;    class InsertPrepared{    public static void main(String args[]){    try{    Class.forName("oracle.jdbc.driver.OracleDriver");    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@loc alhost:1521:xe","system","oracle");      PreparedStatement stmt=con.prepareStatement("insert into Emp value s(?,?)");    stmt.setInt(1,101);//1 specifies the first parameter in the query    stmt.setString(2,"Ratan");    int i=stmt.executeUpdate();    System.out.println(i+" records inserted");    con.close();    }catch(Exception e){ System.out.println(e);}    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 64.  Example of PreparedStatement interface that updates the record  PreparedStatement stmt=con.prepareStatement("update  emp set name=? where id=?");    stmt.setString(1,"Sonoo");//1 specifies the first parameter  in the query i.e. name    stmt.setInt(2,101);        int i=stmt.executeUpdate();    System.out.println(i+" records updated");   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 65.  Example of PreparedStatement interface that deletes the record  PreparedStatement stmt=con.prepareStatement("delete f rom emp where id=?");    stmt.setInt(1,101);        int i=stmt.executeUpdate();    System.out.println(i+" records deleted");   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 66.  Example of PreparedStatement interface that retrieve the records of a table  PreparedStatement stmt=con.prepareStatement("select *  from emp");    ResultSet rs=stmt.executeQuery();    while(rs.next()){    System.out.println(rs.getInt(1)+" "+rs.getString(2));    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 67.  Example of PreparedStatement to insert records until user press n BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 68.  import java.sql.*;    import java.io.*;    class RS{    public static void main(String args[])throws Exception{    Class.forName("oracle.jdbc.driver.OracleDriver");    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521 :xe","system","oracle");    PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));    do{    System.out.println("enter id:");    int id=Integer.parseInt(br.readLine());    System.out.println("enter name:");    String name=br.readLine();    System.out.println("enter salary:");    float salary=Float.parseFloat(br.readLine());    ps.setInt(1,id);    ps.setString(2,name);    ps.setFloat(3,salary);   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 69.  int i=ps.executeUpdate();    System.out.println(i+" records affected");    System.out.println("Do you want to continue: y/n");    String s=br.readLine();    if(s.startsWith("n")){    break;    }    }while(true);    con.close();    }}   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 70. CallableStatement Interface  To call the stored procedures and functions, CallableStatement interface is used.  We can have business logic on the database by the use of stored procedures and functions that will make the performance better because these are precompiled.  Suppose you need the get the age of the employee based on the date of birth, you may create a function that receives date as the input and returns age of the employee as the output. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 71. How to get the instance of CallableStatement?  The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given below:  public CallableStatement prepareCall("{ call procedurena me(?,?...?)}");    The example to get the instance of CallableStatement is given below:  CallableStatement stmt=con.prepareCall("{call myproced ure(?,?)}");    It calls the procedure myprocedure that receives 2 arguments. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 72. ResultSet interface  The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row.  By default, ResultSet object can be moved forward only and it is not updatable.  But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by:  Statement stmt = con.createStatement(ResultSet.TYPE_SCRO LL_INSENSITIVE,                         ResultSet.CONCUR_UPDATABLE);   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 73. Commonly used methods of ResultSet interface BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 74. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 75.  Example of Scrollable ResultSet  Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 76.  import java.sql.*;    class FetchRecord{    public static void main(String args[])throws Exception{      Class.forName("oracle.jdbc.driver.OracleDriver");    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho st:1521:xe","system","oracle");    Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIV E,ResultSet.CONCUR_UPDATABLE);    ResultSet rs=stmt.executeQuery("select * from emp765");    //getting the record of 3rd row    rs.absolute(3);    System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));    con.close();    }}   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 77. ResultSetMetaData Interface  The metadata means data about data i.e. we can get further information from the data.  If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 78. Commonly used methods of ResultSetMetaData interface BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 79.  How to get the object of ResultSetMetaData:  The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:  public ResultSetMetaData getMetaData()throws SQLEx ception   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 80.  import java.sql.*;    class Rsmd{    public static void main(String args[]){    try{    Class.forName("oracle.jdbc.driver.OracleDriver");      Connection con=DriverManager.getConnection(    "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");    PreparedStatement ps=con.prepareStatement("select * from emp");    ResultSet rs=ps.executeQuery();    ResultSetMetaData rsmd=rs.getMetaData();    System.out.println("Total columns: "+rsmd.getColumnCount());    System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));    System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));    con.close();    }catch(Exception e){ System.out.println(e);}    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 81.  Output:Total columns: 2  Column Name of 1st column: ID  Column Type Name of 1st column: NUMBER BY LECTURER SURAJ PANDEY CCT COLLEGE