Unit 5 - JDBC
JDBC Definition
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. JDBC API uses JDBC drivers to connect with the database.
What is API?
API (Application programming interface) is a document that contains a 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
Why Should We Use JDBC?
Before JDBC, ODBC API was the database API to connect and execute the 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).
A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API are given below:
o DriverManager class
o Blob class
o Clob class
o Types class
Activities by using JDBC API to handle database
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
Java Database Connectivity Steps
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dynamically
the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
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)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe",
"system","password");
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.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
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 SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
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
Example to close connection
con.close();
Basic CRUD Operations
Creating, reading, updating, and deleting data in a database is a common task in many
applications, and JDBC (Java Database Connectivity) is a Java API that allows you to connect
to a database and perform these operations.
C – Create
R – Read
U – Update
D – Delete
To Create a Table
Following is the SQL query to create a table.
create table employee(age number(3), name varchar2(40),);
To execute SQL INSERT, SELECT, UPDATE and DELETE statements
Using execute() method to execute general query.
Using executeUpdate() method to execute INSERT, UPDATE or DELETE query
Using executeQuery() method to execute SELECT query.
Using a ResultSet to iterate over rows returned from a SELECT query, using
its next() method to advance to next row in the result set, and using getXXX() methods to
retrieve values of columns.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class CRUD
{
public static void main(String[] args) throws SQLException
{
String url ="jdbc:mysql://localhost:3306/TestDatabase"; //update connection string
String user = "user";//add your db user id here
String password = "password";//add your db password here
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Successfully connected");
//insert employee record into database
Statement stmt = conn.createStatement();
int rows = stmt.executeUpdate("insert into employee(age,name) values(23,'James')");
System.out.println("Rows inserted = "+ rows);
//update employee record
rows= stmt.executeUpdate("Update employee set age=31 where name='James'");
System.out.println("Rows updated = "+ rows);
//read employee records
ResultSet rs = stmt.executeQuery("Select * from employee");
while(rs.next()){
System.out.println("Emp Id : " + rs.getInt("id") + ", Name : " + rs.getString("name") + ",
Age : " + rs.getInt("age"));
}
//delete employee record
rows = stmt.executeUpdate("delete from employee where name = 'James'");
System.out.println("Rows deleted = "+ rows);
}
}
Output
Successfully connected
Rows inserted = 1
Rows updated = 1
Emp Id : 8, Name : John Doe, Age : 21
Emp Id : 10, Name : James, Age : 31
Rows deleted = 1