Components of JDBC

Last updated on Dec 13 2022
Prabhas Ramanathan

Table of Contents

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().

Useful methods of DriverManager class

Method Description
1) public static void registerDriver(Driver driver): is used to register the given driver with DriverManager.
2) public static void deregisterDriver(Driver driver): is used to deregister the given driver (drop the driver from the list) with DriverManager.
3) public static Connection getConnection(String url): is used to establish the connection with the specified url.
4) public static Connection getConnection(String url,String userName,String password): is used to establish the connection with the specified url, username and password.

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.

Commonly used methods of Connection interface:

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.

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.

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.
Example of Statement interface
Let’s see the simple example of Statement interface to insert, update and delete the record.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4. Class.forName(“oracle.jdbc.driver.OracleDriver”);
5. Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”oracle”);
6. Statement stmt=con.createStatement();
7.
8. //stmt.executeUpdate(“insert into emp765 values(33,’Irfan’,50000)”);
9. //int result=stmt.executeUpdate(“update emp765 set name=’Vimal’,salary=10000 where id=33”);
10. int result=stmt.executeUpdate(“delete from emp765 where id=33″);
11. System.out.println(result+” records affected”);
12. con.close();
13. }}

ResultSet interface

The object of ResultSet maintains a cursor pointing to a row of a table. 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:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one row next from the current position.
2) public boolean previous(): is used to move the cursor to the one row previous from the current position.
3) public boolean first(): is used to move the cursor to the first row in result set object.
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column index of the current row as int.
8) public int getInt(String columnName): is used to return the data of specified column name of the current row as int.
9) public String getString(int columnIndex): is used to return the data of specified column index of the current row as String.
10) public String getString(String columnName): is used to return the data of specified column name of the current row as String.

Example of Scrollable ResultSet

Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName(“oracle.jdbc.driver.OracleDriver”);
6. Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”oracle”);
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery(“select * from emp765″);
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+” “+rs.getString(2)+” “+rs.getString(3));
13.
14. con.close();
15. }}

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:
1. 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.

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:
1. public PreparedStatement prepareStatement(String query)throws SQLException{}
Methods of PreparedStatement interface
The important methods of PreparedStatement interface are given below:

Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String value) sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.
public int executeUpdate() executes the query. It is used for create, drop, insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an instance of ResultSet.

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.
7. Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”oracle”);
8.
9. PreparedStatement stmt=con.prepareStatement(“insert into Emp values(?,?)”);
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,”Ratan”);
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+” records inserted”);
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
download this example

Example of PreparedStatement interface that updates the record

1. PreparedStatement stmt=con.prepareStatement(“update emp set name=? where id=?”);
2. stmt.setString(1,”Sonoo”);//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”);
download this example

Example of PreparedStatement interface that deletes the record

1. PreparedStatement stmt=con.prepareStatement(“delete from emp where id=?”);
2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
5. System.out.println(i+” records deleted”);
download this example

 

Example of PreparedStatement interface that retrieve the records of a table

1. PreparedStatement stmt=con.prepareStatement(“select * from emp”);

2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+” “+rs.getString(2));
5. }
download this example

 

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.
8. PreparedStatement ps=con.prepareStatement(“insert into emp130 values(?,?,?)”);
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11.
12. do{
13. System.out.println(“enter id:”);
14. int id=Integer.parseInt(br.readLine());
15. System.out.println(“enter name:”);
16. String name=br.readLine();
17. System.out.println(“enter salary:”);
18. float salary=Float.parseFloat(br.readLine());
19.
20. ps.setInt(1,id);
21. ps.setString(2,name);
22. ps.setFloat(3,salary);
23. int i=ps.executeUpdate();
24. System.out.println(i+” records affected”);
25.
26. System.out.println(“Do you want to continue: y/n”);
27. String s=br.readLine();
28. if(s.startsWith(“n”)){
29. break;
30. }
31. }while(true);
32.
33. con.close();
34. }}

Java 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.

Commonly used methods of ResultSetMetaData interface

Method Description
public int getColumnCount()throws SQLException it returns the total number of columns in the ResultSet object.
public String getColumnName(int index)throws SQLException it returns the column name of the specified column index.
public String getColumnTypeName(int index)throws SQLException it returns the column type name for the specified index.
public String getTableName(int index)throws SQLException it returns the table name for the specified column index.

How to get the object of ResultSetMetaData:

The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:
1. public ResultSetMetaData getMetaData()throws SQLException

Example of ResultSetMetaData interface :

1. import java.sql.*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. Class.forName(“oracle.jdbc.driver.OracleDriver”);
6. Connection con=DriverManager.getConnection(
7. “jdbc:oracle:thin:@localhost:1521:xe”,”system”,”oracle”);
8.
9. PreparedStatement ps=con.prepareStatement(“select * from emp”);
10. ResultSet rs=ps.executeQuery();
11. ResultSetMetaData rsmd=rs.getMetaData();
12.
13. System.out.println(“Total columns: “+rsmd.getColumnCount());
14. System.out.println(“Column Name of 1st column: “+rsmd.getColumnName(1));
15. System.out.println(“Column Type Name of 1st column: “+rsmd.getColumnTypeName(1));
16.
17. con.close();
18. }catch(Exception e){ System.out.println(e);}
19. }
20. }
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER

So, this brings us to the end of blog. This Tecklearn ‘Components of JDBC’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Components of JDBC"

Leave a Message

Your email address will not be published. Required fields are marked *