Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
Experiment No. 6
Title: Connect to a MySQL/Postgres/SQLite database using JDBC to perform basic CRUD
operations
Aim
To design and implement a Java application that connects to a relational database (MySQL /
PostgreSQL / SQLite) using JDBC and performs CRUD operations (Create, Read, Update, Delete)
with transaction handling.
Objectives
• To understand JDBC (Java Database Connectivity) and database drivers.
• To set up and connect Java applications with MySQL, PostgreSQL, or SQLite.
• To perform CRUD operations using PreparedStatement.
• To implement transaction management (commit/rollback).
• To develop a case-study-based Library Management System.
Outcomes
After completing this experiment, the student will be able to:
• Establish a JDBC connection to multiple relational databases.
• Create and manipulate database tables via Java programs.
• Write CRUD operations using PreparedStatement to prevent SQL injection.
• Use transactions for atomic borrow/return operations.
• Switch between embedded (SQLite) and client-server (MySQL/PostgreSQL) databases.
Prerequisite
• Basic SQL knowledge (DDL, DML).
• Java programming (classes, exceptions, I/O).
• JDBC drivers for MySQL, PostgreSQL, or SQLite.
Requirements
• JDK (version 8 or above).
• MySQL / PostgreSQL server, or SQLite installed.
• JDBC driver JARs:
• MySQL: [Link]
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
• PostgreSQL: [Link]
• SQLite: [Link]
• SQL client (phpMyAdmin, pgAdmin, or sqlite3 CLI).
Brief Theory
• JDBC (Java Database Connectivity): A Java API for connecting to relational databases.
• JDBC Drivers: Each DB requires its own driver (e.g., MySQL Connector/J, PostgreSQL
JDBC, SQLite JDBC).
• Connection URL Examples:
• MySQL: jdbc:mysql://localhost:3306/librarydb
• PostgreSQL: jdbc:postgresql://localhost:5432/librarydb
• SQLite: jdbc:sqlite:[Link]
• PreparedStatement: Prevents SQL injection by binding parameters.
• Transactions:
• [Link](false); → Begin transaction
• [Link](); → Save changes
• [Link](); → Revert on error
Laboratory Exercise
Case Study Problem – Campus Library Management System
1. Create database schema
CREATE TABLE books (
book_id SERIAL PRIMARY KEY,
isbn VARCHAR(20) UNIQUE NOT NULL,
title VARCHAR(255) NOT NULL,
author VARCHAR(200),
copies INTEGER DEFAULT 1
);
CREATE TABLE members (
member_id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
email VARCHAR(150) UNIQUE,
join_date DATE DEFAULT CURRENT_DATE
);
CREATE TABLE loans (
loan_id SERIAL PRIMARY KEY,
book_id INTEGER REFERENCES books(book_id),
member_id INTEGER REFERENCES members(member_id),
loan_date DATE DEFAULT CURRENT_DATE,
due_date DATE,
returned BOOLEAN DEFAULT FALSE
);
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
2. Write a Java program with the following features:
• addBook() → INSERT book record
• getBookByISBN() → SELECT query
• updateBookCopies() → UPDATE book copies
• deleteBook() → DELETE record
• borrowBook() → Transaction (decrement book copies + INSERT loan record)
• returnBook() → Transaction (increment copies + mark loan as returned)
3. Use try-with-resources to close connections, statements, and result sets.
4. Demonstrate CRUD operations on all tables with a menu-driven console program.
Sample Java Program (Core Parts)
import [Link].*;
public class LibraryApp {
private static final String URL = "jdbc:sqlite:[Link]"; // Change for
MySQL/Postgres
private static final String USER = "root"; // For MySQL/Postgres
private static final String PASSWORD = "password";
// Establish connection
private static Connection getConnection() throws SQLException {
return [Link](URL, USER, PASSWORD);
}
// Add a book
public static void addBook(String isbn, String title, String author, int
copies) {
String sql = "INSERT INTO books(isbn, title, author, copies)
VALUES(?, ?, ?, ?)";
try (Connection conn = getConnection(); PreparedStatement ps =
[Link](sql)) {
[Link](1, isbn);
[Link](2, title);
[Link](3, author);
[Link](4, copies);
[Link]();
[Link](" Book added successfully.");
} catch (SQLException e) {
[Link](" Error: " + [Link]());
}
}
// Borrow a book (Transaction)
public static void borrowBook(int memberId, int bookId) {
String updateBook = "UPDATE books SET copies = copies - 1 WHERE book_id
= ? AND copies > 0";
String insertLoan = "INSERT INTO loans(book_id, member_id, due_date)
VALUES(?, ?, DATE('now', '+14 day'))";
try (Connection conn = getConnection()) {
[Link](false);
try (PreparedStatement ps1 = [Link](updateBook);
PreparedStatement ps2 = [Link](insertLoan)) {
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
[Link](1, bookId);
int updated = [Link]();
if (updated == 0) {
throw new SQLException("No copies available for book " +
bookId);
}
[Link](1, bookId);
[Link](2, memberId);
[Link]();
[Link]();
[Link](" Book borrowed successfully.");
} catch (SQLException e) {
[Link]();
[Link](" Transaction failed: " + [Link]());
}
} catch (SQLException e) {
[Link](" Connection error: " + [Link]());
}
}
// Main menu (simplified)
public static void main(String[] args) {
addBook("123456", "Effective Java", "Joshua Bloch", 5);
borrowBook(1, 1); // Assume member_id=1, book_id=1
}
}
Steps to Execute
1. Install database (MySQL/Postgres/SQLite).
2. Create librarydb and run the schema SQL.
3. Download and add the respective JDBC driver JAR to classpath.
4. Compile:
javac [Link]
5. Run:
java -cp ".:[Link]" LibraryApp
(Adjust classpath for MySQL/Postgres drivers.)
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
CODE:
import [Link].*;
import [Link];
public class LibraryApp {
private static final String URL = "jdbc:postgresql://localhost:5432/librarydb";
private static final String USER = "postgres";
private static final String PASSWORD = "sumaiya";
static {
try {
[Link]("[Link]");
} catch (ClassNotFoundException e) {
[Link]("❌ PostgreSQL JDBC Driver not found. Include it in
your library path!");
[Link]();
}
}
private static Connection getConnection() throws SQLException {
return [Link](URL, USER, PASSWORD);
}
// ----------------------- BOOK METHODS -----------------------
public static void addBook(String isbn, String title, String author, int cop-
ies) {
String sql = "INSERT INTO books(isbn, title, author, copies) VALUES(?, ?,
?, ?)";
try (Connection conn = getConnection();
PreparedStatement ps = [Link](sql)) {
[Link](1, isbn);
[Link](2, title);
[Link](3, author);
[Link](4, copies);
[Link]();
[Link]("Book added successfully.");
} catch (SQLException e) {
[Link](" Error: " + [Link]());
}
}
public static void viewBooks() {
String sql = "SELECT * FROM books";
try (Connection conn = getConnection();
Statement stmt = [Link]();
ResultSet rs = [Link](sql)) {
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
[Link]("Book List:");
[Link]("%-5s %-15s %-30s %-20s %-6s%n", "ID", "ISBN", "Ti-
tle", "Author", "Copies");
while ([Link]()) {
[Link]("%-5d %-15s %-30s %-20s %-6d%n",
[Link]("book_id"),
[Link]("isbn"),
[Link]("title"),
[Link]("author"),
[Link]("copies"));
}
} catch (SQLException e) {
[Link]("Error: " + [Link]());
}
}
public static void deleteBook(int bookId) {
String deleteLoans = "DELETE FROM loans WHERE book_id = ?";
String deleteBook = "DELETE FROM books WHERE book_id = ?";
try (Connection conn = getConnection()) {
[Link](false);
try (PreparedStatement ps1 = [Link](deleteLoans);
PreparedStatement ps2 = [Link](deleteBook)) {
[Link](1, bookId);
[Link]();
[Link](1, bookId);
int rows = [Link]();
[Link]();
if (rows > 0) {
[Link](" Book and its loans deleted success-
fully.");
} else {
[Link]("Book ID not found.");
}
} catch (SQLException e) {
[Link]();
[Link]("Transaction failed: " + [Link]());
}
} catch (SQLException e) {
[Link]("Connection error: " + [Link]());
}
}
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
public static void getBookByISBN(Scanner sc) {
[Link]("Enter ISBN: ");
String isbn = [Link]();
String sql = "SELECT * FROM books WHERE isbn = ?";
try (Connection conn = getConnection();
PreparedStatement ps = [Link](sql)) {
[Link](1, isbn);
try (ResultSet rs = [Link]()) {
if ([Link]()) {
[Link]("Book Found: ID=%d, Title=%s, Author=%s, Cop-
ies=%d%n",
[Link]("book_id"),
[Link]("title"),
[Link]("author"),
[Link]("copies"));
} else {
[Link]("No book found with ISBN: " + isbn);
}
}
} catch (SQLException e) {
[Link]("Error: " + [Link]());
}
}
// ----------------------- BORROW/RETURN -----------------------
public static void borrowBook(int bookId) {
String sql = "UPDATE books SET copies = copies - 1 WHERE book_id = ? AND copies
> 0";
try (Connection conn = getConnection();
PreparedStatement ps = [Link](sql)) {
[Link](1, bookId);
int updated = [Link]();
if (updated > 0) {
[Link]("Book borrowed successfully!");
} else {
[Link]("Book not available or invalid ID!");
}
} catch (SQLException e) {
[Link]("Error: " + [Link]());
}
}
public static void returnBook(int bookId) {
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
String sql = "UPDATE books SET copies = copies + 1 WHERE book_id = ?";
try (Connection conn = getConnection();
PreparedStatement ps = [Link](sql)) {
[Link](1, bookId);
int updated = [Link]();
if (updated > 0) {
[Link]("Book returned successfully!");
} else {
[Link]("Invalid Book ID!");
}
} catch (SQLException e) {
[Link]("Error: " + [Link]());
}
}
// ----------------------- MAIN MENU -----------------------
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
while (true) {
[Link]("\n=== Library Management Menu ===");
[Link]("1. Add Book");
[Link]("2. View Books");
[Link]("3. Borrow Book");
[Link]("4. Return Book");
[Link]("5. Delete Book");
[Link]("6. Get Book by ISBN");
[Link]("7. Exit");
[Link]("Enter choice: ");
int choice = [Link]();
[Link](); // consume newline
switch (choice) {
case 1 -> {
[Link]("Enter ISBN: ");
String isbn = [Link]();
[Link]("Enter Title: ");
String title = [Link]();
[Link]("Enter Author: ");
String author = [Link]();
[Link]("Enter Copies: ");
int copies = [Link]();
[Link]();
addBook(isbn, title, author, copies);
}
case 2 -> viewBooks();
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
case 3 -> { // Borrow Book
[Link]("Enter Book ID to borrow: ");
int bookId = [Link]();
[Link]();
borrowBook(bookId);
}
case 4 -> { // Return Book
[Link]("Enter Book ID to return: ");
int bookId = [Link]();
[Link]();
returnBook(bookId);
}
case 5 -> {
[Link]("Enter Book ID to delete: ");
int deleteId = [Link]();
[Link]();
deleteBook(deleteId);
}
case 6 -> getBookByISBN(sc);
case 7 -> {
[Link]("Exiting...");
[Link]();
[Link](0);
}
default -> [Link]("Invalid choice. Try again.");
}
}
}
}
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
Output:
Adding new Book:
View Books:
Borrow a Book:
After borrowing a book, the number of available
copies is automatically reduced, as reflected when
you view the books list.
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
View Books
Return Book:
After returning a book, the number of available copies is automatically increased, as shown when
you view the books list.
Name : Sayyed Sumaiya Waqar Rollno : 68 Batch-C
Get Book By ISBN :
Delete Book:
Exit: