[go: up one dir, main page]

0% found this document useful (0 votes)
133 views6 pages

JDBC: Connecting Java to Databases

JDBC stands for Java Database Connectivity and is an API used to connect Java applications to databases. It provides methods and interfaces for communicating with databases like executing queries, storing and manipulating data. The key components are the JDBC API, driver manager, drivers and architecture which involves connecting an application to a database using a driver.

Uploaded by

ridhi gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views6 pages

JDBC: Connecting Java to Databases

JDBC stands for Java Database Connectivity and is an API used to connect Java applications to databases. It provides methods and interfaces for communicating with databases like executing queries, storing and manipulating data. The key components are the JDBC API, driver manager, drivers and architecture which involves connecting an application to a database using a driver.

Uploaded by

ridhi gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Database Connectivity (JDBC): Merging Data from Multiple Tables: Joining,

Manipulating, Databases with JDBC, Prepared Statements, Transaction Processing, Stored


Procedures.

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a specification from Sun Microsystems that
provides a standard abstraction(API or Protocol) for Java applications to
communicate with various databases. It provides the language with Java database
connectivity standards. It is used to write programs required to access databases.
JDBC, along with the database driver, can access databases and spreadsheets. The
enterprise data stored in a relational database(RDB) can be accessed with the help of
JDBC APIs.

Definition of JDBC(Java Database Connectivity)


JDBC is an API(Application programming interface) used in Java programming to
interact with databases. The classes and interfaces of JDBC allow the
application to send requests made by users to the specified database

Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with
databases to store application-specific information. So, 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

There are generally four main components of JDBC through which it can interact
with a database. They are as mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication
with the database. It provides two packages as follows, which contain the java SE
and Java EE platforms to exhibit WORA(write once run anywhere) capabilities.
The [Link] package contains interfaces and classes of JDBC API.

It also provides a standard to connect a database to a client application.


2. JDBC Driver manager: It loads a database-specific driver in an application to
establish a connection with a database. It is used to make a database-specific call to
the database to process the user request.
3. JDBC Test suite: It is used to test the operation(such as insertion, deletion,
updation) being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This
bridge translates the JDBC method call to the ODBC function call. It makes use of
the [Link] package which includes a native library to access ODBC
characteristics.

Architecture of JDBC

Description:
1. Application: It is a java applet or a servlet that communicates with a data
source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL
statements and retrieve results. Some of the important classes and
interfaces defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It
uses some database-specific drivers to effectively connect enterprise
applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you
need a JDBC driver that intelligently communicates with the respective
data source.

JDBC API uses JDBC Drivers to connect with the database.


JDBC Drivers
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 (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver)
Working of JDBC
Java application that needs to communicate with the database has to be programmed
using JDBC API. JDBC Driver supporting data sources such as Oracle and SQL
server has to be added in java application for JDBC support which can be done
dynamically at run time. This JDBC driver intelligently communicates the respective
data source.

//Java program to implement a simple JDBC application

package [Link];

import [Link].*;

public class JDBCDemo {

public static void main(String args[])

throws SQLException, ClassNotFoundException

String driverClassName

= "[Link]";

String url = "jdbc:odbc:XE";

String username = "scott";

String password = "tiger";

String query

= "insert into students values(109, 'bhatt')";

// Load driver class

[Link](driverClassName);

// Obtain a connection

Connection con = [Link](

url, username, password);


// Obtain a statement

Statement st = [Link]();

// Execute the query

int count = [Link](query);

[Link](

"number of rows affected by this query= "

+ count);

// Closing the connection as per the

// requirement with connection is completed

[Link]();

} // class

The above example demonstrates the basic steps to access a database using JDBC.
The application uses the JDBC-ODBC bridge driver to connect to the database. You
must import [Link] package to provide basic SQL functionality and use the classes
of the package.
What is the need of JDBC?
JDBC is a Java database API used for making connection between java applications
with various databases. Basically, JDBC used for establishing stable database
connection with the application API. To execute and process relational database
queries (SQL or Oracle queries), multiple application can connect to different types
of databases which supports both standard (SE) and enterprise (EE) edition of java.

Refer this youtube channel

Merging Data from Multiple Tables

[Link]

: Joining,
Manipulating, Databases with JDBC,

[Link]
Types of Statements in JDBC
The statement interface is used to create SQL basic statements in Java it provides
methods to execute queries with the database. There are different types of statements
that are used in JDBC as follows:
 Create Statement
 Prepared Statement
 Callable Statement
1. Create a Statement: From the connection interface, you can create the object for
this interface. It is generally used for general–purpose access to databases and is
useful while using static SQL statements at runtime.
Syntax:
Statement statement = [Link]();

Implementation: Once the Statement object is created, there are three ways to
execute it.

 boolean execute(String SQL): If the ResultSet object is retrieved, then it


returns true else false is returned. Is used to execute SQL DDL statements
or for dynamic SQL.
 int executeUpdate(String SQL): Returns number of rows that are
affected by the execution of the statement, used when you need a number
for INSERT, DELETE or UPDATE statements.
 ResultSet executeQuery(String SQL): Returns a ResultSet object. Used
similarly as SELECT is used in SQL.

2. Prepared Statement represents a recompiled SQL statement, that can be executed


many times. This accepts parameterized SQL queries. In this, “?” is used instead of
the parameter, one can pass the parameter dynamically by using the methods of
PREPARED STATEMENT at run time.
Illustration:
Considering in the people database if there is a need to INSERT some values, SQL
statements such as these are used:
INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);
To do the same in Java, one may use Prepared Statements and set the values in the ?
holders, setXXX() of a prepared statement is used as shown:

String query = "INSERT INTO people(name, age)VALUES(?, ?)";


Statement pstmt = [Link](query);
[Link](1,"Ayan");
[Link](2,25);
// where pstmt is an object name

Implementation: Once the PreparedStatement object is created, there are three ways
to execute it:
 execute(): This returns a boolean value and executes a static SQL
statement that is present in the prepared statement object.
 executeQuery() : Returns a ResultSet from the current prepared statement.
 executeUpdate() : Returns the number of rows affected by the DML
statements such as INSERT, DELETE, and more that is present in
the current Prepared Statement.

3. Callable Statement are stored procedures which are a group of statements that
we compile in the database for some task, they are beneficial when we are dealing
with multiple tables with complex scenario & rather than sending multiple queries to
the database, we can send the required data to the stored procedure & lower the logic
executed in the database server itself. The Callable Statement interface provided by
JDBC API helps in executing stored procedures.
Syntax: To prepare a CallableStatement
CallableStatement cstmt = [Link]("{call
Procedure_name(?, ?}");
Implementation: Once the callable statement object is created
 execute() is used to perform the execution of the statement.

Common questions

Powered by AI

JDBC (Java Database Connectivity) facilitates communication between Java applications and databases by providing a standard API that Java applications can use to execute SQL queries and retrieve results from databases. The major components of JDBC include: 1) JDBC API: It provides methods and interfaces to Java programs for executing SQL statements and retrieving results. 2) JDBC Driver Manager: It manages communication between applications and the database, establishing connections using database-specific drivers. 3) JDBC Drivers: They are client-side adapters that translate requests from Java programs into a protocol that the DBMS understands. 4) JDBC Test suite: It tests operations like insertion, deletion, and updating performed by JDBC drivers. Using these components, JDBC integrates seamlessly with databases and supports operations across different database management systems .

Using a Type-1 JDBC driver, or JDBC-ODBC bridge driver, involves trade-offs such as compatibility with existing ODBC solutions which can be beneficial for legacy systems, but also introduces performance bottlenecks due to the additional layer of translation from JDBC to ODBC calls. It also requires ODBC drivers on the client machine, limiting its portability and making it less suitable for modern applications. In contrast, a Type-4 JDBC driver, or Thin driver, provides a more direct, efficient native protocol connection to the database using Java. It leverages Java’s platform independence, requires no additional software on the client side, and delivers better performance as it avoids intermediary layers. However, Type-4 drivers might not support every database system as comprehensively as Type-1 drivers could with the right ODBC drivers installed .

Prepared Statements in JDBC are significant because they offer a way to execute SQL queries with parameters, enhancing efficiency and security. Parameterized queries use placeholders, denoted by '?', allowing developers to set values dynamically at runtime using methods like 'setString' or 'setInt'. This reduces SQL injection risks and improves performance by pre-compiling SQL statements, which can be executed multiple times with different parameters. They are beneficial in scenarios requiring repeated query execution with varying parameters, providing both optimization in execution speed and consistency across similar SQL operations .

CallableStatements in JDBC enhance the efficiency of executing complex database operations by enabling the use of stored procedures. Stored procedures are pre-compiled groups of SQL statements stored in the database that perform complex tasks. By invoking stored procedures using CallableStatements, multiple SQL queries or operations can be executed with a single call. This reduces the network overhead and processing time, improves maintainability, and alleviates the need for sending multiple queries from the Java application to the database. Such efficiency is particularly valuable in enterprise systems dealing with extensive database interactions across multiple tables .

Dynamic addition of JDBC drivers at runtime benefits Java applications by providing flexibility and scalability in database connectivity. This capability allows applications to add necessary JDBC drivers as they connect to different databases without recompiling the application, facilitating interactions with new or additional databases seamlessly. A driver can be loaded dynamically when the application identifies the need to connect to a specific data source, adapting to changing database environments and increasing resilience to the applications. Consequently, it reduces development and maintenance efforts while enhancing adaptability in rapidly evolving enterprise IT environments .

The JDBC API exemplifies the 'Write Once, Run Anywhere' (WORA) principle by providing a uniform interface for database connectivity across different relational database management systems (RDBMS). By using JDBC, developers can write Java applications that interact with databases without worrying about database-specific syntax or compatibility issues. The API abstracts the underlying database interactions through a consistent set of interfaces and classes. Developers can deploy these applications on any platform with a compatible JDBC driver, ensuring that once a JDBC-based application is developed, it can operate on any environment that supports Java, fulfilling the WORA philosophy of Java .

The four types of JDBC drivers are: 1) Type-1: JDBC-ODBC bridge drivers that convert JDBC calls to ODBC calls. These are largely obsolete and only useful for applications targeting older systems. 2) Type-2: Native-API drivers that convert JDBC calls into native database calls. They require native libraries to be installed on the client machine, making them platform-specific but faster than Type-1. 3) Type-3: Network Protocol drivers, which send JDBC calls to a middleware server that translates them to database-specific calls. They provide flexibility and are fully Java, allowing for greater portability. 4) Type-4: Thin drivers are pure Java drivers that communicate directly with the database using its networking protocol. They are efficient and offer high performance without the need for native libraries, making them the most popular choice for modern applications .

Using SQL DDL (Data Definition Language) operations through the 'execute' method in a JDBC Statement object allows Java applications to perform database schema alterations, such as creating or dropping tables. The 'execute' method returns a boolean indicating whether the operation returned a ResultSet. DDL operations typically do not return result sets, enabling developers to alter database structures straightforwardly within Java applications. This capability is crucial in dynamically changing database schemas in response to application requirements but requires careful management to ensure data integrity and application stability during schema changes .

The DriverManager class in JDBC plays a crucial role by managing a list of database drivers. It facilitates database connections by using these database-specific drivers to establish connections between Java applications and databases. DriverManager locates and loads the appropriate driver by invoking the 'getConnection' method with the database URL, username, and password, enabling applications to execute SQL queries. It abstracts the complexity of driver management and ensures that an application can connect to databases by dynamically finding and loading the required drivers at runtime. This promotes flexibility and adaptability in enterprise applications interacting with multiple types of databases .

The JDBC Test suite ensures effective operation of JDBC drivers by providing a standardized way to test SQL operations such as insertion, deletion, and updating within databases. This suite checks whether the drivers can execute these operations correctly and efficiently. By offering predefined testing scenarios, it aids in verifying the compatibility and functionality of JDBC drivers across different database systems, ensuring that drivers meet the expectations of database connectivity and operations. This process helps maintain the reliability of an application’s interaction with various databases, ensuring consistent performance and behavior .

You might also like