0% found this document useful (0 votes)
54 views

What Is JDBC?: Java Database Connectivity Api Allows Us To Work With Relational

The document discusses Java Database Connectivity (JDBC), which is a Java API that allows Java programs to connect to and interact with relational databases. It discusses the main steps in establishing a JDBC connection, including loading the driver, getting a connection, creating a statement object, executing queries, and closing the connection. It also describes different types of JDBC drivers and key JDBC objects like Connection, Statement, and ResultSet.

Uploaded by

Somenath Majhi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

What Is JDBC?: Java Database Connectivity Api Allows Us To Work With Relational

The document discusses Java Database Connectivity (JDBC), which is a Java API that allows Java programs to connect to and interact with relational databases. It discusses the main steps in establishing a JDBC connection, including loading the driver, getting a connection, creating a statement object, executing queries, and closing the connection. It also describes different types of JDBC drivers and key JDBC objects like Connection, Statement, and ResultSet.

Uploaded by

Somenath Majhi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

What is JDBC?

One of the first JDBC interview question in most of interviews. JDBC is


java database connectivity as name implies it’s a java API for communicating
to relational database, API has java classes and interfaces using that
developer can easily interact with database. For this we need database
specific JDBC drivers.

What are the main steps in java to make JDBC connectivity?

· Load the Driver: First step is to load the database specific driver which
communicates with database.
· Make Connection: Next step is get connection from the database using
connection object, which is used to send SQL statement also and get result
back from the database.
· Get Statement object: From connection object we can get statement
object which is used to query the database
· Execute the Query:Using statement object we execute the SQL or
database query and get result set from the query.
· Close the connection:After getting resultset and all required operation
performed the last step should be closing the database connection.

What is JDBC API and when do we use it?

Java DataBase Connectivity API allows us to work with relational


databases. JDBC API interfaces and classes are part
of java.sql and javax.sql package. We can use JDBC API to get the database
connection, run SQL queries and stored procedures in the database server
and process the results.
JDBC API is written in a way to allow loose coupling between our Java
program and actual JDBC drivers that make our life easier in switching from
one database to another database servers easily.
What are different types of JDBC Drivers?

There are four types of JDBC drivers. Any java program that works with
database has two parts, first part is the JDBC API and second part is the
driver that does the actual work.

1. JDBC-ODBC Bridge plus ODBC Driver (Type 1): It uses ODBC driver to
connect to database. We should have ODBC drivers installed to connect to
database, that’s why this driver is almost obsolete.
2. Native API partly Java technology-enabled driver (Type 2): This driver
converts JDBC class to the client API for the database servers. We should
have database client API installed. Because of extra dependency on database
client API drivers, this is also not preferred driver.
3. Pure Java Driver for Database Middleware (Type 3): This driver sends the
JDBC calls to a middleware server that can connect to different type of
databases. We should have a middleware server installed to work with this
driver. This adds to extra network calls and slow performance and that’s why
not widely used JDBC driver.
4. Direct-to-Database Pure Java Driver (Type 4): This driver converts the
JDBC calls to the network protocol understood by the database server. This
solution is simple and suitable for database connectivity over the network.
However for this solution, we should use database specific drivers, for
example OJDBC jars by Oracle for Oracle DB and MySQL Connector/J for
MySQL databases.

What is JDBC Connection? Explain steps to get Database connection in a


simple java program.

JDBC Connection is like a Session created with the database server. You can
also think Connection is like a Socket connection from the database server.
Creating a JDBC Connection is very easy and requires two steps:

1. Register and Load the Driver: Using Class.forName(), Driver class is


registered to the DriverManager and loaded in the memory.
2. Use DriverManager to get the Connection object: We get connection object
from DriverManager.getConnection() by passing Database URL String,
username and password as argument.

package com.journaldev.jdbc.statements;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

public final static String DB_DRIVER_CLASS = "com.mysql.jdbc.Driver";


public final static String DB_URL = "jdbc:mysql://localhost:3306/UserDB";
public final static String DB_USERNAME = "pankaj";
public final static String DB_PASSWORD = "pankaj123";

public static Connection getConnection() throws ClassNotFoundException,


SQLException {

Connection con = null;

// load the Driver Class


Class.forName(DB_DRIVER_CLASS);
// create the connection now
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);

System.out.println("DB Connection created successfully");


return con;
}
}

What is the use of JDBC DriverManager class?

JDBC DriverManager is the factory class through which we get the Database
Connection object. When we load the JDBC Driver class, it registers itself to
the DriverManager, you can look up the JDBC Driver classes source code to
check this.
Then when we call DriverManager.getConnection() method by passing the
database configuration details, DriverManager uses the registered drivers to
get the Connection and return it to the caller program.

How to get the Database server details in java program?

We can use DatabaseMetaData object to get the database server details.


When the database connection is created successfully, we can get the meta
data object by calling getMetaData() method. There are so many methods in
DatabaseMetaData that we can use to get the database product name, it’s
version and configuration details.

DatabaseMetaData metaData = con.getMetaData();


String dbProduct = metaData.getDatabaseProductName();
What is JDBC Statement?

JDBC API Statement is used to execute SQL queries in the database. We


can create the Statement object by calling
Connection createStatement() method. We can use Statement to execute
static SQL queries by passing query through different execute methods such
as execute(), executeQuery(), executeUpdate() etc.
Since the query is generated in the java program, if the user input is not
properly validated it can lead to SQL injection issue, more details can be
found at SQL Injection Example.
By default, only one ResultSet object per Statement object can be open at the
same time. Therefore, if we want to work with multiple ResultSet objects, then
each must have been generated by different Statement objects. All execute()
methods in the Statement interface implicitly close a statment’s current
ResultSet object if an open one exists.

What is the difference between execute, executeQuery, executeUpdate?

Statement execute(String query) is used to execute any SQL query and it returns TRUE if the
result is an ResultSet such as running Select queries. The output is FALSE when there is no
ResultSet object such as running Insert or Update queries. We can use getResultSet() to get the
ResultSet and getUpdateCount() method to retrieve the update count.
Statement executeQuery(String query) is used to execute Select queries and returns the
ResultSet.

ResultSet returned is never null even if there are no records matching the query. When
executing select queries we should use the executeQuery method so that if someone tries to
execute insert/update statement it will throw java.sql.SQLException with message
“executeQuery method cannot be used for update”.

Statement executeUpdate(String query) is used to execute Insert/Update/Delete (DML)


statements or DDL statements that returns nothing. The output is int and equals the row count
for SQL Data Manipulation Language (DML) statements. For DDL statements, the output is 0.

You should use execute() method only when you are not sure about the type of statement else
use executeQuery or executeUpdate method.
What is JDBC ResultSet?

JDBC ResultSet is like a table of data representing a database result set, which
is usually generated by executing a statement that queries the database.
ResultSet object maintains a cursor pointing to its current row of data. Initially,
the cursor is positioned before the first row. The next() method moves the
cursor to the next row. If there are no more rows, next() method returns false
and it can be used in a while loop to iterate through the result set.
A default ResultSet object is not updatable and has a cursor that moves
forward only. Thus, you can iterate through it only once and only from the first
row to the last row. It is possible to produce ResultSet objects that are
scrollable and/or updatable using below syntax.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_UPDATABLE);

A ResultSet object is automatically closed when the Statement object that


generated it is closed, re-executed, or used to retrieve the next result from a
sequence of multiple results.
We can use ResultSet getter method with column name or index number
starting from 1 to retrieve the column data.

What are different types of ResultSet?

There are different types of ResultSet objects that we can get based on the
user input while creating the Statement. If you will look into the Connection
methods, you will see that createStatement() and prepareStatement() method
are overloaded to provide ResultSet type and concurrency as input argument.
There are three types of ResultSet object.
1. ResultSet.TYPE_FORWARD_ONLY: This is the default type and cursor can
only move forward in the result set.
2. ResultSet.TYPE_SCROLL_INSENSITIVE: The cursor can move forward and
backward, and the result set is not sensitive to changes made by others to the
database after the result set was created.
3. ResultSet.TYPE_SCROLL_SENSITIVE: The cursor can move forward and
backward, and the result set is sensitive to changes made by others to the
database after the result set was created.

Based on the concurrency there are two types of ResultSet object.

1. ResultSet.CONCUR_READ_ONLY: The result set is read only, this is the


default concurrency type.
2. ResultSet.CONCUR_UPDATABLE: We can use ResultSet update method to
update the rows data.

You might also like