JDBC
JDBC
Introduction
• Java application cannot directly communicate with database
• This is because a database can interpret only SQL statements and not java
language statements for this reason, we need a mechanism to translate java
statements into SQL statements
• JDBC API provides the mechanism for the kind of translation
• JDBC stands for Java Database Connectivity
• It is a standard Java API for database-independent connectivity between the
Java programming language and a wide range of databases
Why JDBC API
• Two issues :
1) Java applications cannot directly communicate with a database.
2) Java application should be database independent.
JDBC API uses driver to address the above issues.
How?
• JDBC API takes care of converting java Commands to generic SQL statements.
• JDBC API uses drivers provided by Database vendors to communicate with
database.
• Java Application invokes methods JDBC API.
JDBC
Categories of JDBC drivers
There are several categories of JDBC drivers provided by different database vendors:
1) JDBC-ODBC driver:-
• Database server contain the ODBC driver embedded into them.
• ODBC APIs are written in C language and makes the use of pointers and other
constructs that JAVA doesnot support.
• Hence JDBC-ODBC bridge driver are used to translate the JDBC API to the
ODBC API.
2) Native API partly Java Driver:
Supplied by vendors of database like DB2,Informix provides JDBC drivers in
terms of classes that are directly invoked by JDBC API.
3) Native protocol pure java driver/JDBC-Net pure java driver:
These drivers are used to connect a client application or applet to a database
over a TCP/IP connection.
JDBC Driver Manager
• It is a backbone of the JDBC architecture.
• The function of JDBC driver manager are to maintain a list of drivers created
for different databases and
• Connect a Java application to appropriate driver specified in a Java program.
JDBC-ODBC bridge:
• It is implemented as the JdbcOdbc.class and a native library is used to access
the ODBC driver.
• In a Windows platform ,native library is JDBCODBC.dll.
ACCESS MS-ACCESS
JDBC-ODBC DRIVER
Application JDBC Driver
BRIDGE
Manager
DRIVER
SQL DRIVER MS-SQL
• Ex:
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
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");
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
Calling a method:
con.close();
JDBC program to insert record
in a stud table of database
Student
Import java.sql.*; //Execute a query
public class JDBCDEMO System.out.println("Creating statement...");