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

5.3 JDBC Drivers - connectivity

JDBC Drivers - connectivity

Uploaded by

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

5.3 JDBC Drivers - connectivity

JDBC Drivers - connectivity

Uploaded by

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

JDBC Drivers

• JDBC (Java Database Connectivity) drivers enable Java applications to interact with
databases.
• These drivers act as a bridge between the Java application and the database.
• They convert the high-level JDBC API calls into database-specific calls that can be
understood by the underlying database.
• There are four types of JDBC drivers, each offering different methods of
communication between Java applications and databases.
• Below is a detailed explanation of each JDBC driver types:

1. Type 1: JDBC-ODBC Bridge Driver

The Type 1 driver translates JDBC calls into ODBC (Open Database Connectivity) calls.
ODBC is a standard API for accessing database management systems (DBMS).

• Example:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:DSNName",
"username", "password");

2. Type 2: Native-API Driver (Partially Java-Enabled Driver)

The Type 2 driver converts JDBC calls into database-specific native API calls. The
communication between the Java application and the database happens through the database's
native protocol.

• Example:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"username", "password");

3. Type 3: Network Protocol Driver

The Type 3 driver uses a middleware server that translates JDBC calls into the database's native
protocol. The middleware server allows the client (Java application) to communicate with any
type of database over a network using a standardized network protocol.

• Example:
Class.forName("com.informix.jdbc.IfxDriver");
Connection conn = DriverManager.getConnection("jdbc:informix-
sqli://localhost:1526/testdb:INFORMIXSERVER=myserver", "username",
"password");
4. Type 4: Thin Driver (Pure Java Driver)

The Type 4 driver is a pure Java driver that directly translates JDBC calls into the database's
native protocol. There is no intermediary layer or native code involved, which makes it a high-
performance option.

• Example:
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"root", "password");

Database Connectivity in Java

Database connectivity in Java refers to the process of establishing a connection between a


Java application and a database to perform operations like querying, updating, inserting, and
deleting data.

Java provides several APIs and methods for database interaction, with JDBC (Java Database
Connectivity) being the most common and widely used approach.

In Java, database connectivity is achieved through JDBC, which provides a standard interface
for interacting with relational databases.

It allows Java applications to send SQL queries to the database and process the results.

Steps for Database Connectivity in Java using JDBC


1. Load the Database Driver

• Before establishing a connection to the database, the JDBC driver for the specific
database must be loaded into the application.
• This driver is responsible for translating Java commands into commands that the
database can understand.

For example:

• For MySQL, you would load the MySQL JDBC driver:


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

• For Oracle, you would load the Oracle JDBC driver:


Class.forName("oracle.jdbc.driver.OracleDriver");
2. Establish a Connection

• The next step is to establish a connection to the database using the


DriverManager.getConnection() method.

• You need to provide the database URL, username, and password.

Example (for MySQL):


Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"password");

• The URL specifies the database server and database name.


• The username and password are used for authentication.
3. Create a Statement Object

• Once the connection is established, a Statement object is created to send SQL queries
to the database.

Example:
Statement stmt = conn.createStatement();

4. Execute SQL Queries

• You can execute SQL queries using the Statement object. There are three main
methods for executing queries:
o executeQuery(): Used for executing SELECT queries that return a result set.

o executeUpdate(): Used for executing INSERT, UPDATE, DELETE queries, and other
SQL commands that do not return a result set.
o execute(): Used for executing a general SQL query (returns a boolean indicating
whether the query is a result set or not).

Example of executing a SELECT query:


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

Example of executing an UPDATE query:


int rowsAffected = stmt.executeUpdate("UPDATE users SET name =
'John' WHERE id = 1");
5. Process the Result Set

• When executing a SELECT query, the results are returned as a ResultSet object. This
object allows you to iterate through the result and access the data.

Example:
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

• The next() method moves the cursor to the next row of the result set, and you can
access the column values using methods like getInt(), getString(), etc.
6. Close the Connection

• Once the database operations are completed, you should close the ResultSet,
Statement, and Connection objects to release the database resources.

Example:
rs.close();
stmt.close();
conn.close();
Example Code: Connecting to MySQL Database

Below is a complete example that connects to a MySQL database, retrieves some data, and
processes the result:
import java.sql.*;

public class DatabaseConnectivityExample {


public static void main(String[] args) {
// Step 1: Load the MySQL JDBC driver
try {
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish the connection


Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb","root", "password");

// Step 3: Create a Statement object


Statement stmt = conn.createStatement();

// Step 4: Execute a SELECT query


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

// Step 5: Process the ResultSet


while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

// Step 6: Close resources


rs.close();
stmt.close();
conn.close();

} catch (ClassNotFoundException | SQLException e) {


e.printStackTrace();
}
}
}
Types of SQL Queries in JDBC

1. SELECT: Used to retrieve data from the database.


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

2. INSERT: Used to insert new data into the database.


int rowsAffected = stmt.executeUpdate("INSERT INTO users (name, age)
VALUES ('Alice', 30)");

3. UPDATE: Used to update existing data in the database.


int rowsAffected = stmt.executeUpdate("UPDATE users SET age = 31 WHERE
name = 'Alice'");

4. DELETE: Used to delete data from the database.


int rowsAffected = stmt.executeUpdate("DELETE FROM users WHERE name =
'Alice'");

Using PreparedStatement for Parameterized Queries

• When dealing with dynamic queries, such as when input from users is involved, it's
recommended to use a PreparedStatement.
• This helps prevent SQL injection attacks and also allows the reuse of SQL queries.

Example:

String query = "SELECT * FROM users WHERE name = ?";


PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, "Alice");
ResultSet rs = pstmt.executeQuery();

Transaction Management in JDBC

• JDBC supports transaction management, allowing you to commit or roll back database
changes to ensure data consistency and integrity.

To begin a transaction:
conn.setAutoCommit(false); // Disable auto-commit

To commit the transaction:


conn.commit();
To roll back the transaction:
conn.rollback();

Don't forget to set auto-commit back to true once the transaction is complete:
conn.setAutoCommit(true);
Handling Exceptions in JDBC

• It’s important to handle exceptions in JDBC.


• The most common exception is SQLException, which provides detailed information
about errors that occur during database operations.

Example of exception handling:


try {
// JDBC code here
} catch (SQLException e) {
e.printStackTrace(); // Handle database-related errors
} catch (ClassNotFoundException e) {
e.printStackTrace(); // Handle driver loading errors
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy