0% found this document useful (0 votes)
43 views60 pages

JDBC

Uploaded by

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

JDBC

Uploaded by

Pavan karthik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

JDBC

Java Database Connectivity


Java Database Connectivity (JDBC)
• Introduction to JDBC: Setting up the database, connecting to a
Database: The Connection Interface, connecting to the database using
Driver Manager, Querying and Updating the Database: Statement
Interface, Result Set Interface, Querying and Updating the Database
What is JDBC?
• JDBC stands for Java Database Connectivity
• A standard API for accessing databases from Java applications
• Supports various databases such as Oracle, MySQL, and SQL Server
• JDBC abstracts the database access mechanism
• Allows Java programs to be database-independent.
Purpose of JDBC
• Connect Java applications to relational databases
• Execute SQL statements from Java code
• Fetch data from databases and process results
• Insert, update, delete records in the database
• Manage database connections and resources effectively
Benefits of JDBC
• Cross-platform compatibility
• Write once, connect to any database with minimal changes
• Easy to learn and integrate into Java applications
• Supports transaction management and batch processing
• Extensive error handling with SQLException
Common JDBC Use Cases
• Web-based applications with a backend database
• Enterprise applications needing data storage and retrieval
• Desktop applications with local databases
• Reporting systems accessing data in real-time
• Integration with legacy databases using JDBC-ODBC bridge
JDBC Architecture Overview

• JDBC API is a bridge between Java and databases


• The architecture consists of the JDBC Driver Manager and Driver
• JDBC Drivers handle database communication
• Java code interacts with the JDBC API, which uses SQL queries
• JDBC Driver translates API calls into database-specific instructions
Setting Up the
Database
Prerequisites for JDBC
• Install the required RDBMS (Oracle, MySQL, etc.)
• Set up the database system on your machine or server
• Download and configure the JDBC driver for your database
• Verify the JDBC driver is compatible with your Java version
• Ensure you have SQL privileges to create and modify tables
Database Configuration Steps
• Step 1: Install the database software
• Step 2: Create the necessary tables and schemas
• Step 3: Enable network access to the database
• Step 4: Create user accounts and assign privileges
• Step 5: Test the SQL connection manually before coding JDBC
Sample Database Setup
• Example: MySQL installation
• Create a test database with simple tables
• Tables: students, courses, grades
• SQL example:
• CREATE TABLE students (id INT, name VARCHAR(50), grade INT);
• Populate sample data: INSERT INTO students VALUES (1, 'John Doe',
90);
JDBC Driver Setup
• Download the appropriate JDBC driver for your database
• Include the JDBC driver JAR file in your project’s classpath
• For MySQL: mysql-connector-java-x.x.xx-bin.jar
• For Oracle: ojdbcx.jar
• Ensure that the driver is compatible with the Java version in use
Connecting to a
Database
Overview of Database Connection
• JDBC API is used to connect to databases
• Java program interacts with the database through a Connection
object
• DriverManager is responsible for establishing connections
• Connection requires URL, username, and password
• Once connected, execute SQL queries and update the database
JDBC Connection Process
• Step 1: Load the JDBC driver class
• Step 2: Use DriverManager to create a connection
• Step 3: Create a Statement object for queries
• Step 4: Execute the query using the Statement object
• Step 5: Retrieve results using the ResultSet object
Loading the JDBC Driver
• Load the driver using Class.forName(driverName)
• Example for MySQL: Class.forName("com.mysql.cj.jdbc.Driver");
• Registers the driver with DriverManager
• This step is required to initiate the database connection
• Ensures that Java is aware of the driver’s existence
Connecting to the Database
• Use the DriverManager.getConnection() method
• Connection URL format: jdbc:mysql://localhost:3306/mydatabase
• Provide database credentials: username and password

• Handle connection exceptions using SQLException


Example Code for Connecting to
Database

• Ensure the database server is running before connecting


• Handle connection issues using a try-catch block
• Always close the connection after performing operations
• Demo
• https://www.youtube.com/watch?v=7v2OnUti2eM
The Connection
Interface
Overview of Connection Interface
• Represents a session between Java application and database
• Used to execute SQL statements and retrieve results
• Connection interface has methods for transaction management
• Manage database connection lifecycle: open and close connections
• Create Statement, PreparedStatement, and CallableStatement
Connection Interface Methods
• createStatement(): Create a basic SQL query
• prepareStatement(): Create parameterized SQL queries
• commit(): Commit a transaction
• rollback(): Rollback to a previous state in case of failure
• close(): Close the connection and release resources
Managing Database Transactions
• Transactions allow for grouping multiple SQL queries
• JDBC supports commit and rollback methods
• Use setAutoCommit(false) for manual transaction control
• Use commit() to save changes to the database
• Use rollback() to undo changes if errors occur
Example Code for Transactions

• Handle exceptions to rollback changes if errors occur


• Ensure data consistency by using transactions
Closing Database Connection
• Always close connections using con.close()
• Closing prevents memory leaks and resource exhaustion
• Use finally block to ensure the connection is closed
• Closing a connection also closes Statements and ResultSets
• Best practice: Connection pooling for performance optimization
Connecting to
Database using
DriverManager
Overview of DriverManager
• DriverManager manages the set of JDBC drivers
• Responsible for establishing database connections
• It matches the database URL with the appropriate driver
• Automatically handles loading and unloading drivers
• Supports multiple database drivers in one application
DriverManager Methods
• getConnection(url, user, pass): Establishes a connection to the
database
• registerDriver(driver): Manually registers a JDBC driver
• deregisterDriver(driver): Removes a driver from DriverManager
• getDriver(url): Returns the driver instance for the specified URL
• getLoginTimeout(): Specifies how long to wait for a connection
Registering Drivers with
DriverManager
• Drivers can be registered manually or automatically
• Manual registration

• Automatic registration via Class.forName()


Managing Multiple Drivers
• DriverManager can handle multiple database drivers
• Application can connect to different databases concurrently
• Ensure the correct driver is used by specifying the correct URL
• Example: One app using MySQL and PostgreSQL drivers
• Manage driver loading and connection handling carefully
Example Code for DriverManager

• Handle exceptions and check for driver issues


• Always check if the driver supports the database URL

• Demo
https://www.geeksforgeeks.org/establishing-jdbc-connection-in-java/
Querying and Updating
the Database
Introduction to SQL Queries in JDBC
• JDBC allows executing SQL queries to interact with the database
• Queries include SELECT, INSERT, UPDATE, DELETE
• Queries are executed using the Statement or PreparedStatement
interface
• Data retrieved is stored in a ResultSet object
• Always handle SQL exceptions with proper error handling
The Statement Interface
• Used to execute basic SQL queries
• Methods:
• executeQuery(sql) – for SELECT queries
• executeUpdate(sql) – for INSERT, UPDATE, DELETE queries
• execute(sql) – for complex queries with multiple results
• Suitable for simple SQL commands without parameters
PreparedStatement for
Parameterized Queries
• PreparedStatement is used for parameterized queries
• Precompiles the SQL query for better performance
• Avoids SQL injection attacks by using placeholders (?)

• Used for queries that are executed multiple times


Updating the Database
• executeUpdate() is used for INSERT, UPDATE, DELETE queries
• It returns the number of affected rows in the database
• Use executeUpdate for all DML operations

• Always handle exceptions when updating the database


• Demo https://www.w3schools.com/sql/sql_update.asp
Example Code for Querying and
Updating
• Querying with Statement

• Updating with PreparedStatement


PreparedStatement pstmt = con.prepareStatement("UPDATE students SET
grade = ? WHERE id = ?");
pstmt.setInt(1, 95);
pstmt.setInt(2, 1);
int rows = pstmt.executeUpdate();
The ResultSet Interface
Introduction to ResultSet
• ResultSet holds the results of SQL queries
• Represents data in a tabular format (rows and columns)
• Cursors are used to navigate through the result set
• ResultSet can be read-only or scrollable
• Data is accessed using get() methods (e.g., getInt(), getString())
Types of ResultSet
• TYPE_FORWARD_ONLY: Can only move forward in the result set
• TYPE_SCROLL_INSENSITIVE: Can scroll forward and backward; does
not reflect changes made by others
• TYPE_SCROLL_SENSITIVE: Can scroll and reflect changes made by
others
• Choose the type based on the application's needs
• Concurrency modes: CONCUR_READ_ONLY or CONCUR_UPDATABLE
Navigating the ResultSet
• Common methods for navigating the ResultSet:
• next() – Move to the next row
• previous() – Move to the previous row
• first() – Move to the first row
• last() – Move to the last row
• beforeFirst() – Move before the first row
• afterLast() – Move after the last row
Retrieving Data from ResultSet
• Use getInt(), getString(), getFloat(), etc., to retrieve column data

• Always use the correct method for the column type


Closing the ResultSet
• Always close the ResultSet to release resources
• Closing the ResultSet automatically closes the Statement object
• Use rs.close() to explicitly close it
• Ensure all database resources are freed after use
• Closing helps prevent memory leaks and excessive resource
consumption
• Demo https://
www.digitalocean.com/community/tutorials/java-resultset
Querying and Updating
with
PreparedStatement
Introduction to PreparedStatement
• PreparedStatement allows for precompiled, parameterized queries
• Offers better performance than Statement
• Helps prevent SQL injection attacks
• Supports both DML and DQL operations
• Widely used in real-time applications
Creating PreparedStatement
• Use Connection.prepareStatement(sql) to create a PreparedStatement
• Replace values in SQL query with ? (placeholders)
• Bind parameters using setInt(), setString(), etc.
• Example:
PreparedStatement pstmt = con.prepareStatement("INSERT INTO students (id,
name, grade) VALUES (?, ?, ?)");
pstmt.setInt(1, 101);
pstmt.setString(2, "John Doe");
pstmt.setInt(3, 95);
pstmt.executeUpdate();
Benefits of PreparedStatement
• Precompiled SQL statements improve performance
• Can be reused for multiple executions with different parameters
• Offers better security by avoiding SQL injection
• Easier to maintain and modify complex queries
• Suitable for executing batch operations
• Demo
• https://www.javatpoint.com/PreparedStatement-interface
Executing PreparedStatement
Queries
• Use executeQuery() for SELECT queries
• Use executeUpdate() for INSERT, UPDATE, DELETE queries
• Example
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM students
WHERE grade > ?");
pstmt.setInt(1, 90);
ResultSet rs = pstmt.executeQuery();
Updating the Database with
PreparedStatement
• Example
PreparedStatement pstmt = con.prepareStatement("UPDATE students SET
grade = ? WHERE id = ?");
pstmt.setInt(1, 85);
pstmt.setInt(2, 101);
int rowsUpdated = pstmt.executeUpdate();
System.out.println("Rows updated: " + rowsUpdated);
• Always use PreparedStatement for complex queries and dynamic
input
Best Practices for JDBC
Connection Pooling
• Use connection pooling to optimize resource usage
• Connection pools reuse existing connections instead of creating new
ones
• Reduces the overhead of establishing connections repeatedly
• Widely used in high-traffic applications
• Examples of connection pool libraries: HikariCP, Apache DBCP
Exception Handling in JDBC
• Always handle SQLException in JDBC code
• Use try-catch-finally blocks to ensure resources are released
• Example of catching SQLException:

• Handle specific SQL errors like invalid syntax and connection failures
Closing Resources
• Always close Connection, Statement, and ResultSet objects
• Use try-with-resources in Java 7+ for automatic resource
management

• Closing resources prevents memory leaks and ensures proper cleanup


Security Best Practices
• Use PreparedStatement to prevent SQL injection
• Avoid hard-coding credentials in your code
• Store sensitive data like passwords securely
• Use SSL/TLS encryption for database connections
• Ensure proper privilege management for database users
Performance Optimization in JDBC
• Use batch processing to handle multiple queries efficiently
• Optimize SQL queries to reduce database load
• Use connection pooling for better resource management
• Avoid unnecessary auto-commit operations for better performance
• Properly index tables in the database to optimize query execution
Summary
Summary of JDBC Concepts
• JDBC allows Java applications to interact with databases
• Supports both SQL querying and database updates
• Offers a wide range of functionality, including transactions and batch
processing
• Provides different interfaces for different query types (Statement,
PreparedStatement, etc.)
Recap of Key Components
• JDBC API provides a standard method to access databases
• DriverManager manages database drivers and connections
• Connection interface represents the communication session
• Statement and PreparedStatement are used to execute SQL queries
• ResultSet is used to handle data retrieved from queries
Advantages of Using JDBC
• Cross-platform compatibility allows for universal database access
• Provides a secure and efficient way to query and update databases
• JDBC’s transaction management ensures data integrity
• Handles multiple database drivers in a single application
• Simplifies database access in Java enterprise applications
JDBC in Real-World Applications
• Commonly used in web applications with a relational database
backend
• Supports enterprise-level data processing
• JDBC is used in a variety of industries, from finance to e-commerce
• Enables seamless integration with legacy databases using ODBC
bridges
Closing Remarks
• JDBC is an essential API for database-driven applications in Java
• Its flexibility and robustness make it a popular choice for developers
• Mastering JDBC enables you to build data-centric applications

You might also like