Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Module-3 JDBC Concepts

Uploaded by

Rupith Kumar .N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Module-3 JDBC Concepts

Uploaded by

Rupith Kumar .N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Prepared by Mr. Lohith C, Professor, Department of Dr.

APJ Kalam School of Engineering

Subject: Advanced Java and J2EE


Module 3-JDBC Concepts
Prepared By Mr. Lohith C
Professor
Dept of APJ Abdul Kalam School of Engineering
Garden City University

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

The Concept of JDBC (Java Database Connectivity)


1. What is JDBC?

JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect to
and interact with relational databases (like MySQL, Oracle, PostgreSQL). It provides
methods to execute SQL queries, retrieve data, and manage database transactions.

2. Key Components of JDBC

 Driver: Software component that handles the communication with the database.
 Connection: Establishes a connection between the Java application and the database.
 Statement: Used to execute SQL queries.
 ResultSet: Stores the results of SQL queries.
 SQLException: Handles database-related exceptions.

3. JDBC Architecture

1. Application Layer: Java code interacts with JDBC API.


2. JDBC Driver Manager: Manages the drivers and connections.
3. JDBC Drivers: Implements the communication protocol for a specific database.
4. Database Layer: The actual database where data is stored.

4. Types of JDBC Drivers

1. Type 1 – JDBC-ODBC Bridge Driver:


o Connects to databases via ODBC.
o Slow and deprecated in newer versions.
2. Type 2 – Native-API Driver:
o Uses database-specific native libraries.
o Faster than Type 1 but platform-dependent.
3. Type 3 – Network Protocol Driver:
o Uses middleware server for communication.
o Good for web applications.
4. Type 4 – Thin Driver (Pure Java Driver):
o Directly communicates with the database.
o Platform-independent and widely used (e.g., MySQL, PostgreSQL drivers).

5. Steps to Connect a Java Program to a Database Using JDBC

1. Load the Driver:

java
Copy code
Class.forName("com.mysql.cj.jdbc.Driver");

2. Establish a Connection:

java
Copy code

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Connection conn = DriverManager.getConnection(


"jdbc:mysql://localhost:3306/mydb", "username", "password");

3. Create a Statement:

java
Copy code
Statement stmt = conn.createStatement();

4. Execute a Query:

java
Copy code
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

5. Process the ResultSet:

java
Copy code
while (rs.next()) {
System.out.println(rs.getString("username"));
}

6. Close the Connection:

java
Copy code
conn.close();

6. JDBC Interfaces

 DriverManager: Manages database drivers and establishes connections.


 Connection: Represents the connection to the database.
 Statement: Used to execute SQL queries.
 PreparedStatement: A pre-compiled SQL statement that prevents SQL injection.
 ResultSet: Stores the result of a SQL query.

7. Types of Statements

1. Statement:
o Executes static SQL queries.

java
Copy code
Statement stmt = conn.createStatement();
stmt.executeQuery("SELECT * FROM users");

2. PreparedStatement:
o Executes parameterized queries, which improves security and performance.

java
Copy code

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users


WHERE id = ?");
pstmt.setInt(1, 10);
ResultSet rs = pstmt.executeQuery();

3. CallableStatement:
o Used to call stored procedures from a database.

java
Copy code
CallableStatement cstmt = conn.prepareCall("{call getUserById(?)}");
cstmt.setInt(1, 5);
ResultSet rs = cstmt.executeQuery();

8. ResultSet Object

 ResultSet is used to retrieve data from SQL queries.


 Common Methods:
o next(): Moves to the next row.
o getString(columnName): Gets a string value from the column.
o getInt(columnIndex): Gets an integer value from the specified column
index.

9. Handling Transactions in JDBC

 Transactions group multiple SQL operations to ensure atomicity (all-or-nothing).

Example of a transaction:

java
Copy code
conn.setAutoCommit(false); // Disable auto-commit

try {
stmt.executeUpdate("INSERT INTO users VALUES (1, 'John')");
stmt.executeUpdate("INSERT INTO accounts VALUES (1, 1000)");
conn.commit(); // Commit the transaction
} catch (SQLException e) {
conn.rollback(); // Roll back on error
}

10. Exception Handling in JDBC

 SQLException is the main exception class.


 Handle exceptions using try-catch blocks:

java
Copy code
try {
Connection conn = DriverManager.getConnection(...);
} catch (SQLException e) {
e.printStackTrace();

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

11. Advantages of JDBC

 Platform-independent: Works on any system with a compatible driver.


 Supports Multiple Databases: MySQL, Oracle, PostgreSQL, etc.
 Secure: PreparedStatement prevents SQL injection.
 Scalable: Can be used in large-scale enterprise applications.

12. Limitations of JDBC

 Requires boilerplate code for establishing connections and handling results.


 Not well-suited for object-relational mapping (ORM), where frameworks like
Hibernate are more efficient.
 Managing connection pools can be complex in large applications.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

JDBC Driver Types


JDBC drivers are software components that enable Java applications to interact with
databases. There are four types of JDBC drivers, each with unique architecture and features.
Let's explore them in detail:

1. Type 1: JDBC-ODBC Bridge Driver

 How it works: Converts JDBC calls into ODBC (Open Database Connectivity)
calls, allowing Java to interact with databases through ODBC drivers.
 Architecture:
Java Application → JDBC API → ODBC Driver → Database

Advantages:

 Easy to set up if an ODBC driver is available.


 Useful for accessing older databases.

Disadvantages:

 Platform-dependent (requires ODBC driver installed).


 Slow due to additional translation between JDBC and ODBC.
 Deprecated and removed in later versions of Java (from Java 8 onwards).

2. Type 2: Native-API Driver

 How it works: Converts JDBC calls into database-specific native library calls.
 Architecture:
Java Application → JDBC API → Native Library (DB-specific) → Database

Advantages:

 Faster than Type 1 as it uses native libraries for direct communication.


 Suitable for applications where native performance is crucial.

Disadvantages:

 Platform-dependent (native libraries must be installed for each OS).


 Limited portability across platforms.
 Harder to maintain in enterprise environments.

3. Type 3: Network Protocol Driver (Middleware Driver)

 How it works: Uses a middleware server that translates JDBC calls into database-
specific protocol.
 Architecture:
Java Application → JDBC API → Middleware Server → Database

Advantages:

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

 Database-agnostic: Middleware server can manage multiple types of databases.


 More scalable and useful in distributed applications.

Disadvantages:

 Requires a separate middleware server, increasing system complexity.


 Slightly slower due to the added network overhead between the application and
middleware.

4. Type 4: Thin Driver (Pure Java Driver)

 How it works: Converts JDBC calls directly into the database’s native protocol.
 Architecture:
Java Application → JDBC API → Database

Advantages:

 Platform-independent (written entirely in Java).


 Faster than other drivers since it communicates directly with the database.
 No additional libraries or middleware required.

Disadvantages:

 Requires a separate driver for each database (e.g., MySQL, PostgreSQL).


 If the database protocol changes, the driver needs updates.

Comparison of JDBC Driver Types

Aspect Type 1 Type 2 Type 3 Type 4


JDBC-ODBC Network Protocol
Name Native-API Driver Thin Driver
Bridge Driver
Performance Slow Faster than Type 1 Moderate Fast
Platform
Yes Yes No No
Dependency
Native performance Distributed Modern
Use Case Legacy systems
required applications applications
Driver Requires native Requires Easy to
Deprecated
Maintenance libraries middleware maintain

Which Driver to Use?

 Type 4 Driver is the most commonly used today because it is platform-


independent, easy to use, and provides high performance.
 Type 3 Drivers are used in distributed or multi-database environments where a
middleware server is available.
 Type 1 and Type 2 Drivers are largely obsolete due to their platform dependency
and maintenance challenges.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

JDBC Packages Overview


Java provides two core packages for JDBC-related functionality:

 java.sql
 javax.sql

These packages contain essential interfaces and classes that help establish connections,
execute SQL statements, manage transactions, and retrieve query results.

1. java.sql Package

The java.sql package provides the core functionality for interacting with relational
databases.

Key Interfaces and Classes in java.sql

1. DriverManager
o Manages JDBC drivers and establishes connections.

java
Copy code
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "user", "password");

2. Connection
o Represents a connection to the database.
o Methods:
 createStatement(): Creates a Statement object.
 prepareStatement(): Creates a PreparedStatement.
 setAutoCommit(): Enables/disables auto-commit mode.
 close(): Closes the connection.
3. Statement
o Used to execute static SQL queries.

java
Copy code
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

4. PreparedStatement
o Used for parameterized SQL queries to improve performance and prevent SQL
injection.

java
Copy code
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 101);
ResultSet rs = pstmt.executeQuery();

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

5. CallableStatement
o Used to call stored procedures from the database.

java
Copy code
CallableStatement cstmt = conn.prepareCall("{call getUserById(?)}");
cstmt.setInt(1, 5);
ResultSet rs = cstmt.executeQuery();

6. ResultSet
o Stores results of SQL queries.
o Methods:
 next(): Moves the cursor to the next row.
 getString(), getInt(): Retrieve column values by name or index.
7. SQLException
o Handles exceptions that occur during database operations.

java
Copy code
try {
Connection conn = DriverManager.getConnection(...);
} catch (SQLException e) {
e.printStackTrace();
}

8. Date, Time, and Timestamp Classes


o Used to handle SQL date/time data types:
 java.sql.Date
 java.sql.Time
 java.sql.Timestamp

2. javax.sql Package

The javax.sql package provides advanced JDBC functionality, focusing on connection


pooling, distributed transactions, and RowSet implementations.

Key Interfaces and Classes in javax.sql

1. DataSource
o An alternative to DriverManager for establishing connections, often used with
connection pools.

java
Copy code
DataSource ds = new MysqlDataSource();
Connection conn = ds.getConnection();

2. ConnectionPoolDataSource
o Provides connections from a connection pool, improving performance in high-
demand environments.
3. PooledConnection

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

o Represents a physical connection to the database that can be reused.


4. RowSet Interface and Implementations
o A wrapper around ResultSet with added functionality.
 JdbcRowSet: Connected RowSet similar to ResultSet.
 CachedRowSet: Disconnected RowSet that stores data in memory.
 WebRowSet: A RowSet that can be serialized as XML.
5. XADataSource and XAConnection
o Supports distributed transactions across multiple databases.

Summary of JDBC Packages and Their Use Cases

Package Description Use Case

java.sql Core JDBC functionality like connections and queries Basic database operations

Advanced features: connection pooling, RowSets, Enterprise applications with


javax.sql
transactions scalability

When to Use Each Package

 Use java.sql for standard database operations like queries and updates.
 Use javax.sql when working with enterprise-level applications, connection pooling, or
distributed systems.

These packages provide all the tools needed to interact with databases efficiently and handle
different application requirements—from simple queries to high-performance enterprise
solutions.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Brief Overview of the JDBC Process


The JDBC process involves a series of steps to connect a Java application to a relational
database and perform database operations (like querying and updating data). Below is a
streamlined explanation of the key steps in the JDBC process.

Steps in the JDBC Process

1. Load the JDBC Driver

 This step ensures that the appropriate JDBC driver is loaded into memory.
 Example:

java
Copy code
Class.forName("com.mysql.cj.jdbc.Driver");

This registers the MySQL JDBC driver with the DriverManager.

2. Establish a Connection

 Use the DriverManager class to create a connection to the database.


 Example:

java
Copy code
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "user", "password");

The getConnection() method returns a Connection object used to interact with the
database.

3. Create a Statement or PreparedStatement

 Use the Connection object to create a Statement or PreparedStatement to execute


SQL queries.
 Statement (for static queries):

java
Copy code
Statement stmt = conn.createStatement();

 PreparedStatement (for dynamic/parameterized queries):

java
Copy code
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 101);

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

4. Execute SQL Queries

 Use the Statement or PreparedStatement object to run SQL queries.


 For SELECT Queries (which return a ResultSet):

java
Copy code
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

 For INSERT, UPDATE, DELETE Queries:

java
Copy code
int rowsAffected = stmt.executeUpdate(
"INSERT INTO users (id, name) VALUES (101, 'Alice')");

5. Process the Results

 If the query returns a ResultSet, iterate through it to retrieve the data.

java
Copy code
while (rs.next()) {
System.out.println("User ID: " + rs.getInt("id"));
System.out.println("User Name: " + rs.getString("name"));
}

6. Handle Exceptions (Optional)

 Use try-catch blocks to manage SQLExceptions and other errors.

java
Copy code
try {
Connection conn = DriverManager.getConnection(...);
} catch (SQLException e) {
e.printStackTrace();
}

7. Close the Resources

 Always close the ResultSet, Statement, and Connection objects to free up


resources.

java
Copy code
rs.close();
stmt.close();
conn.close();

JDBC Process Flow Diagram

1. Load the JDBC Driver →


2. Establish a Connection →
3. Create a Statement/PreparedStatement →

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

4. Execute SQL Queries →


5. Process Results (if any) →
6. Handle Exceptions (if needed) →
7. Close Resources

Summary

The JDBC process enables Java applications to interact with databases by following these
steps:

1. Load the JDBC driver.


2. Establish a connection.
3. Create a statement.
4. Execute queries.
5. Process results.
6. Handle exceptions (optional).
7. Close resources.

This simple, step-by-step process allows developers to efficiently perform CRUD


operations (Create, Read, Update, Delete) on databases.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

JDBC with MySQL


Database Connection

A connection represents the session between a Java application and the database.
Establishing a connection is the first step in interacting with the database.

Steps to Connect to MySQL Database:

1. Load the MySQL JDBC Driver:

java
Copy code
Class.forName("com.mysql.cj.jdbc.Driver");

This step registers the MySQL driver with the DriverManager.

2. Establish a Connection:

java
Copy code
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "username", "password");

o URL format: jdbc:mysql://<host>:<port>/<database_name>


o username/password: Database credentials

Associating the JDBC/ODBC Bridge with the Database

 JDBC-ODBC Bridge (Type 1 driver) allows Java to connect to databases through an


ODBC driver. However, this driver is deprecated and not recommended for modern
applications.
 For MySQL, use Type 4 driver (pure Java driver) such as:

xml
Copy code
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.x</version>
</dependency>

Make sure the MySQL Connector/J is added to your project classpath.

Statement Objects

A Statement is used to send SQL queries to the database.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Types of Statement Objects:

1. Statement: Used for simple SQL queries without parameters.

java
Copy code
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

2. PreparedStatement: Used for pre-compiled, parameterized queries to improve


performance and prevent SQL injection.

java
Copy code
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 101);
ResultSet rs = pstmt.executeQuery();

3. CallableStatement: Used to call stored procedures in the database.

java
Copy code
CallableStatement cstmt = conn.prepareCall("{call getUserById(?)}");
cstmt.setInt(1, 5);
ResultSet rs = cstmt.executeQuery();

ResultSet

The ResultSet object holds the result of a SELECT query and provides methods to access
and manipulate the data.

Common Methods of ResultSet:

 next(): Moves the cursor to the next row.


 getString(columnName): Retrieves the value of the specified column as a string.
 getInt(columnIndex): Retrieves the value of the specified column as an integer.

Example:

java
Copy code
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id"));
System.out.println("Name: " + rs.getString("name"));
}

Transaction Processing

Transactions ensure that a group of operations is executed atomically—either all operations


succeed, or none.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Steps for Handling Transactions:

1. Disable Auto-Commit Mode:

java
Copy code
conn.setAutoCommit(false);

2. Execute Queries:

java
Copy code
stmt.executeUpdate("INSERT INTO accounts VALUES (1, 'Alice', 5000)");
stmt.executeUpdate("INSERT INTO transactions VALUES (1, 'Deposit',
5000)");

3. Commit the Transaction:

java
Copy code
conn.commit();

4. Rollback in Case of Errors:

java
Copy code
conn.rollback();

Metadata

Metadata provides information about the database and the result set.

Database Metadata:

 Obtained using the DatabaseMetaData interface.


 Example:

java
Copy code
DatabaseMetaData dbMeta = conn.getMetaData();
System.out.println("Database Product Name: " +
dbMeta.getDatabaseProductName());

ResultSet Metadata:

 Provides information about the columns in a ResultSet.


 Example:

java
Copy code
ResultSetMetaData rsMeta = rs.getMetaData();
int columnCount = rsMeta.getColumnCount();
for (int i = 1; i <= columnCount; i++) {

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

System.out.println("Column Name: " + rsMeta.getColumnName(i));


}

Data Types

MySQL supports various data types for storing information. Here are the most common
types:

 String Types: CHAR, VARCHAR, TEXT


 Numeric Types: INT, BIGINT, FLOAT, DOUBLE
 Date/Time Types: DATE, DATETIME, TIMESTAMP
 Boolean Type: BOOLEAN (stored as TINYINT(1))

Example of a MySQL Table Schema:

sql
Copy code
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Exception Handling

Exceptions can occur during database operations, such as connection issues, SQL syntax
errors, or query failures. JDBC uses the SQLException class to handle these exceptions.

Handling SQL Exceptions:


java
Copy code
try {
Connection conn = DriverManager.getConnection(...);
Statement stmt = conn.createStatement();
stmt.executeQuery("SELECT * FROM users");
} catch (SQLException e) {
System.out.println("SQL Error: " + e.getMessage());
e.printStackTrace();
} finally {
// Close resources
}

Summary of JDBC Process with MySQL

1. Database Connection: Load the driver and establish a connection.


2. Statement Objects: Create a Statement, PreparedStatement, or CallableStatement.
3. Execute Queries: Run SQL commands (e.g., SELECT, INSERT).
4. Process ResultSet: Iterate through the query results.
5. Transaction Processing: Use commit and rollback for atomic operations.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

6. Metadata: Access database and result set details.


7. Data Types: Use MySQL-compatible data types.
8. Exception Handling: Manage SQLExceptions to handle database errors gracefully.

These concepts are essential for building Java applications that interact with MySQL
databases efficiently and reliably.

Sample Code of JDBC with MySQL


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.logging.Level;

import java.util.logging.Logger;

public class Database {

String jdbcdriver = "";

String dbURL = "";

String username = "";

String password = "";

Connection connection;

public Database() throws ClassNotFoundException, SQLException

jdbcdriver = "com.mysql.jdbc.Driver";

dbURL = "jdbc:mysql://localhost:3306/dbexample";

username = "root";

password = "root";

//1. JDBC Driver

Class.forName(jdbcdriver);

//2. connection with database

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

connection = DriverManager.getConnection(dbURL,username,password);

//3. Prepare a statements or query

public ResultSet executeQuery(String query) throws SQLException

PreparedStatement st = connection.prepareStatement(query);

return st.executeQuery();

public int executeUpdate(String statement) throws SQLException

PreparedStatement st = connection.prepareStatement(statement);

return st.executeUpdate();

//4. close connection

public void close()

try {

connection.close();

} catch (SQLException ex) {

Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);

Garden City University

You might also like