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

Database Connectivity in Java and JDBC

Uploaded by

Vikas Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Database Connectivity in Java and JDBC

Uploaded by

Vikas Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Database Connectivity in Java and JDBC

Vikas Chandra Sharma, Swarrnim School of Computing & IT, Swarrnim Startup and Innovation
University

Introduction to JDBC (Java Database Connectivity)


Java Database Connectivity (JDBC) is a standard API in Java that allows Java applications to
connect to various databases, execute SQL queries, and retrieve results. JDBC is part of the
Java Standard Edition (Java SE), providing a uniform interface to work with different
databases such as MySQL, Oracle, PostgreSQL, and SQL Server.
1. JDBC Architecture
The JDBC architecture includes:
 JDBC API: Provides methods to connect to a database, execute queries, and retrieve
data.
 JDBC Driver: A software component enabling Java applications to interact with the
database. There are four types of JDBC drivers:
o Type 1: JDBC-ODBC bridge
o Type 2: Native-API driver
o Type 3: Network Protocol driver
o Type 4: Thin driver (pure Java)
Typically, Type 4 drivers are used as they are platform-independent and suitable for various
databases.
2. JDBC API Components
Key components in the JDBC API include:
 DriverManager: Manages JDBC drivers and establishes database connections.
 Connection: Represents a session with a database, allowing SQL statements to be
executed.
 Statement: Used for executing static SQL queries (e.g., Statement,
PreparedStatement, CallableStatement).
 ResultSet: Holds data retrieved from a database, enabling data manipulation.
 SQLException: Handles SQL-related errors and exceptions.
3. Steps to Connect Java with Database using JDBC
To establish a database connection and perform CRUD operations, follow these steps:
Step 1: Import JDBC Packages
java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
Step 2: Load and Register JDBC Driver
For a specific database (e.g., MySQL), load the driver:
java
Copy code
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Step 3: Establish a Connection
java
Copy code
String url = "jdbc:mysql://localhost:3306/database_name";
String user = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, user, password);
Step 4: Create a Statement
Use the Statement or PreparedStatement to execute SQL queries.
java
Copy code
Statement statement = connection.createStatement();
Step 5: Execute Queries
Use SQL queries for database operations:
 Insert Data:
java
Copy code
String sqlInsert = "INSERT INTO students (id, name, age) VALUES (1, 'John Doe', 20)";
statement.executeUpdate(sqlInsert);
 Retrieve Data:
java
Copy code
String sqlSelect = "SELECT * FROM students";
ResultSet resultSet = statement.executeQuery(sqlSelect);
while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") +
", Name: " + resultSet.getString("name") +
", Age: " + resultSet.getInt("age"));
}
 Update Data:
java
Copy code
String sqlUpdate = "UPDATE students SET age = 21 WHERE id = 1";
statement.executeUpdate(sqlUpdate);
 Delete Data:
java
Copy code
String sqlDelete = "DELETE FROM students WHERE id = 1";
statement.executeUpdate(sqlDelete);
Step 6: Close Connections
Close the ResultSet, Statement, and Connection to release resources.
java
Copy code
resultSet.close();
statement.close();
connection.close();
4. Using PreparedStatement
PreparedStatement is a parameterized SQL statement that improves performance and security
by preventing SQL injection.
Example of using PreparedStatement:
java
Copy code
String sql = "INSERT INTO students (id, name, age) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 2);
preparedStatement.setString(2, "Jane Doe");
preparedStatement.setInt(3, 22);
preparedStatement.executeUpdate();
preparedStatement.close();
5. JDBC Transaction Management
Transactions ensure data integrity by grouping multiple operations into a single unit of work.
Transactions can be committed or rolled back.
java
Copy code
try {
connection.setAutoCommit(false);
statement.executeUpdate("UPDATE students SET age = 23 WHERE id = 2");
statement.executeUpdate("DELETE FROM students WHERE id = 1");
connection.commit();
} catch (SQLException e) {
connection.rollback();
e.printStackTrace();
} finally {
connection.setAutoCommit(true);
}
Complete Example: JDBC Program to Perform CRUD Operations
java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String password = "rootpassword";

try {
// Load driver and establish connection
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);

// Insert data
String insertSQL = "INSERT INTO students (id, name, age) VALUES (?,?,?)";
PreparedStatement insertStatement = connection.prepareStatement(insertSQL);
insertStatement.setInt(1, 1);
insertStatement.setString(2, "Alice");
insertStatement.setInt(3, 19);
insertStatement.executeUpdate();

// Retrieve and display data


String selectSQL = "SELECT * FROM students";
Statement selectStatement = connection.createStatement();
ResultSet resultSet = selectStatement.executeQuery(selectSQL);
while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") +
", Name: " + resultSet.getString("name") +
", Age: " + resultSet.getInt("age"));
}

// Update data
String updateSQL = "UPDATE students SET age = 20 WHERE id = 1";
Statement updateStatement = connection.createStatement();
updateStatement.executeUpdate(updateSQL);

// Delete data
String deleteSQL = "DELETE FROM students WHERE id = 1";
Statement deleteStatement = connection.createStatement();
deleteStatement.executeUpdate(deleteSQL);

// Close connections
resultSet.close();
insertStatement.close();
selectStatement.close();
updateStatement.close();
deleteStatement.close();
connection.close();

} catch (ClassNotFoundException | SQLException e) {


e.printStackTrace();
}
}
}
Exercises:
1. Connecting to a Database:
o Write a Java program that connects to a database and creates a new table
named employees with fields for id, name, and position.
2. CRUD Operations:
o Write Java methods to perform CRUD operations on an employees table:
 addEmployee(int id, String name, String position)
 getEmployee(int id)
 updateEmployee(int id, String newPosition)
 deleteEmployee(int id)
3. PreparedStatement Usage:
o Create a program using PreparedStatement that inserts multiple records into
the employees table, retrieving them to verify the entries.
4. Transaction Management:
o Write a Java program that uses transactions to transfer "salary" from one
employee to another, rolling back if the transaction fails.
Long Answer Questions:
1. Explain the JDBC Architecture and its components. How does each component
contribute to database connectivity in Java?
o JDBC Architecture consists of the JDBC API, drivers, DriverManager,
Connection, Statement, and ResultSet. The API provides the methods, while
the driver enables the Java program to interact with databases. DriverManager
manages database drivers, and Connection represents the session. Statement is
used to execute queries, and ResultSet holds data retrieved from the database.
Together, these components allow for seamless interaction between Java
applications and databases.
2. What is the significance of PreparedStatement in JDBC? How does it enhance
performance and security compared to Statement?
o PreparedStatement improves performance by pre-compiling SQL queries and
reusing them with different parameters. It also prevents SQL injection attacks
by using parameterized queries, where data and query structure are separate,
ensuring safer database interactions.
3. Describe how transactions are managed in JDBC. Provide a scenario where
transaction management is necessary and explain the role of commit() and
rollback().
o Transaction management in JDBC ensures data integrity by grouping
operations into a single unit, with the option to either commit() (confirm
changes) or rollback() (revert changes) in case of an error. For instance, in a
banking application, transferring money between accounts requires multiple
steps. If any step fails, a rollback ensures no partial transactions occur,
maintaining a consistent state.

You might also like