JDBC Introduction
JDBC Introduction
JDBC :
❖ JDBC API is a Java API that can access any kind of tabular data,
especially data stored in a Relational Database.
❖ JDBC works with Java on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX.
❖ JDBC stands for Java Database Connectivity, which is a standard Java
API for database-independent connectivity between the Java
programming language and a wide range of databases.
❖ The JDBC library includes APIs for each of the tasks mentioned below
that are commonly associated with database usage.
● Making a connection to a database.
● Creating SQL or MySQL statements.
● Executing SQL or MySQL queries in the database.
● Viewing & Modifying the resulting records.
Applications of JDBC :
Fundamentally, JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database. Java can be used to write different
types of executables, such as −
● Java Applications
● Java Applets
● Java Servlets
● Java ServerPages (JSPs)
● Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database,
and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code. Interacting with a database requires efficient database
connectivity, which can be achieved by using the ODBC(Open database connectivity) driver.
This driver is used with JDBC to interact or communicate with various kinds of databases
such as Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC :
JDBC drivers are client-side adapters (installed on the client machine, not on the
server) that convert requests from Java programs to a protocol that the DBMS can
understand. There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
Type-1 Driver : Type-1 driver or 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.
Type-1 driver is also called Universal driver
because it can be used to connect to any of
the databases.
●As a common driver is used in order to
interact with different databases, the data
transferred through this driver is not so
secured.
●The ODBC bridge driver is needed to be
installed in individual client machines.
●Type-1 driver isn’t written in java, that’s
why it isn’t a portable driver.
Vendor based database libraries means you need to use ●It is a database independent driver.
libraries provided by vendors to connect to database. For
example You need to use ojdbc6.jar for Oracle ,
postgresql-9.4.1207.jar for postgresql etc
Type-2 Driver : The Native API driver uses the client
-side libraries of the database. This
driver converts JDBC method calls
into native calls of the database API.
In order to interact with different
database, this driver needs their local
API, that’s why data transfer is much
more secure as compared to type-1
driver.
● Driver needs to be installed
separately in individual client
machines
● The Vendor client library needs to
be installed on client machine.
● Type-2 driver isn’t written in java,
that’s why it isn’t a portable driver
● It is a database dependent driver.
Type-3 Driver : The Network Protocol driver uses middleware
(application server) that converts JDBC calls
directly or indirectly into the vendor-specific
database protocol. Here all the database
connectivity drivers are present in a single
server, hence no need of individual client-side
installation.
● Type-3 drivers are fully written in
Java, hence they are portable drivers.
● No client side library is required
because of application server that can
perform many tasks like auditing, load
balancing, logging etc.
● Network support is required on client
machine.
● Maintenance of Network Protocol
driver becomes costly because it
requires database-specific coding to
be done in the middle tier.
● Switch facility to switch over from one
database to another database.
Type-4 Driver : Type-4 driver is also called native protocol driver. This driver
interact directly with database. It does not require any native
database library, that is why it is also known as Thin Driver.
● Does not require any native library and Middleware
server, so no client-side or server-side installation.
● It is fully written in Java language, hence they are
portable drivers.
Working
They are basically used in a web-based application that has 3 tier architecture. The position at which the application server fits in is
described below:
● Tier 1 – This is a GUI interface that resides at the client end and is usually a thin client (e.g. browser)
● Tier 2 – This is called the middle tier, which consists of the Application Server.
● Tier 3 – This is the 3rd tier which is backend servers. E.g., a Database Server.
As we can see, they usually communicate with the webserver for serving any request that is coming from
clients. The client first makes a request, which goes to the webserver. The web server then sends it to the
middle tier, i.e. the application server, which further gets the information from 3 rd tier (e.g. database server)
and sends it back to the webserver. The web server further sends back the required information to the client.
Different approaches are being utilized to process requests through the web servers, and some of them are
approaches like JSP (Java server pages), CGI(Common Gateway Interface), ASP (Active Server Pages), Java
Scripts, Java servlets, etc.
Common JDBC Components
Connection
cn=DriverManager.getConnection(URL);
Commonly used methods of Connection interface
Method Description
public Statement createStatement(); creates a statement object that can be
Ex. Statement st=cn.createStatement(); used to execute SQL queries.
• There are 5 steps to connect any java application with the database in java
using JDBC. They are as follows:
Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method. Ex.
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
2. Creating connection
• The DriverManager.getConnection() method is used to establish connection with the
database.
con.close();
//WAP to display data of student table
import java.sql.*;
class ConnectAccess1Demo{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(“Select * from student”);
while(rs.next())
{
System.out.println(“RollNo. : ” + getInt(1));
System.out.println(“Name : ” + getString(2));
}
cn.close();
}
//WAP to create table using jdbc
import java.sql.*;
class ConnectAccess1Demo{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
Statement st=cn.createStatement();
String str= “Create table emp(emp_name varchar(20), emp_id number)”
st.executeUpdate(str);
System.out.println(“Table created” );
cn.close();
}
}
//WAP to insert data into emp table
import java.sql.*;
class ConnectAccess1Demo{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
Statement st=cn.createStatement();
st.executeUpdate(“insert into emp values(“abc”,1)”);
st.executeUpdate(“insert into emp values(“pqr”,2)”);
System.out.println(“Records inserted” );
cn.close();
}
}
//WAP to crate table, insert and display data into emp table
import java.sql.*;
class ConnectAccess1Demo{
public static void main(String args[]) throws Exception
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
Statement st=cn.createStatement();
String str= “Create table emp(emp_name varchar(20), emp_id number)”
st.executeUpdate(str);
System.out.println(“Table created” );
st.executeUpdate(“insert into emp values(“abc”,1)”);
st.executeUpdate(“insert into emp values(“pqr”,2)”);
System.out.println(“Records inserted” );
ResultSet rs= “select * from emp”;
st.executeQuery();
while(rs.next())
{System.out.println(“Emp_ID : ” + getInt(2));
System.out.println(“Emp_Name : ” + getString(1));
}
cn.close(); }
Steps to Connect Java Application with
mysql database example
1. Create 2 folders : lib and src on C drive
2. Download Sql connector [MySQL :: Download Connector/J]
And select Operating system - platform independent , Download its zip folder, Extract
that folder, and copy “mysql-connector-j-8.1.0” executable jar file to C:\db\lib folder
3. Download xamppserver and start - Apache and MySQL
4. To create database in MySQL click Admin button in front of
xamppserver
5. Create a new database student_db here
Then create table student_info having fields
enrollNo, name, dept, division
6. Write and save program RetrieveStudentInfo.java
in src folder
import java.sql.Connection;
8.
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RetrieveStudentInfo {
public static void main(String[] args) {
// Database connection parameters
Class.forName("com.mysql.jdbc.Driver");
String jdbcURL = "jdbc:mysql://localhost:3306/student_db";
String username = "root";
String password = "";
// SQL query to retrieve values
String sqlQuery = "SELECT enrollNo, name, dept, division FROM student_info";
try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
ResultSet resultSet = preparedStatement.executeQuery()) {
// Loop through the result set and print values
while (resultSet.next()) {
int enrollNo = resultSet.getInt("enrollNo");
String name = resultSet.getString("name");
String dept = resultSet.getString("dept");
String division = resultSet.getString("division");
/*System.out.println("EnrollmentNo : " + enrollNo + ", StudentName : " + name +
",Department : " + dept + ",Division : " + division); */
System.out.println(enrollNo +" "+ name +" "+ dept +" "+ division);
} } catch (SQLException e) { e.printStackTrace(); } }}
public void setDouble(int paramIndex, double sets the double value to the given parameter index.
value)
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.
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
1. create table student(roll_no number(10), name varchar2(50));
Now insert records in this table by the code given below:
import java.sql.*;
class UpdateDemo{
public static void main(String args[])
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
PreparedStatement p=cn.prepareStatement( "insert into student values (?,?)" );
p.setInt(1,10);
p.setInt(1,20);
p.setString(2,"abc");
p.setString(2,"pqr");
p.executeUpdate();
System.out.println("values inserted");
}}
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
1. create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:
1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
7. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
8. stmt.setInt(1,101);//1 specifies the first parameter in the query
9. stmt.setString(2,"Rtan");
10. int i=stmt.executeUpdate();
11. System.out.println(i+" records inserted");
12. con.close(); }catch(Exception e){ System.out.println(e);} } }
Example of PreparedStatement to insert records until user press n
1. import java.sql.*;
2. import java.io.*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
7. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9. do{
10. System.out.println("enter id:");
11. int id=Integer.parseInt(br.readLine());
12. System.out.println("enter name:");
13. String name=br.readLine();
14. System.out.println("enter salary:");
15. float salary=Float.parseFloat(br.readLine());
1. ps.setInt(1,id);
2. ps.setString(2,name);
3. ps.setFloat(3,salary);
4. int i=ps.executeUpdate();
5. System.out.println(i+" records affected");
6.
7. System.out.println("Do you want to continue: y/n");
8. String s=br.readLine();
9. if(s.startsWith("n")){
10. break;
11. }
12. }while(true);
13.
14. con.close();
15. }}
Example of PreparedStatement interface that updates the record
1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
2. stmt.setString(1,"Ratna");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
if (row > 0) {
System.out.println("A row has been inserted successfully.");
}
sql = "SELECT * FROM Contacts";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
int id = result.getInt("Contact_ID");
String fullname = result.getString("Full_Name");
String email = result.getString("Email");
String phone = result.getString("Phone");
System.out.println(id + ", " + fullname + ", " + email + ", " + phone);
}
} catch (SQLException ex) {
ex.printStackTrace();
} }}