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

Week 8 Ass.

The document provides code examples for performing various database operations using JDBC in Java: 1. Establishing a connection to a MySQL database and printing success or failure. 2. Implementing an airline reservation system that allows user registration and flight booking using a database. 3. Retrieving student details from a database by executing a query and iterating through the result set. 4. Retrieving all records from a database table by executing a query and printing the results. 5. Inserting a new record into a database table by preparing an INSERT statement with placeholders and values.

Uploaded by

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

Week 8 Ass.

The document provides code examples for performing various database operations using JDBC in Java: 1. Establishing a connection to a MySQL database and printing success or failure. 2. Implementing an airline reservation system that allows user registration and flight booking using a database. 3. Retrieving student details from a database by executing a query and iterating through the result set. 4. Retrieving all records from a database table by executing a query and printing the results. 5. Inserting a new record into a database table by preparing an INSERT statement with placeholders and values.

Uploaded by

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

Week 8 – Tutorial Assignment

DECLARATIVE PROGRAMMING PARADIGM


SUHANA GUHA

RA2211047010015

1. Write a simple application program to establish JDBC connection.


Code
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class JDBCDemo {

public static void main(String[] args) {

// Define database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase"; // Replace with your database URL

String username = "your_username";

String password = "your_password";

// Initialize the connection

try {

// Load the MySQL JDBC driver (you need to have the JDBC driver JAR in your classpath)

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

// Establish the database connection

Connection connection = DriverManager.getConnection(jdbcUrl, username, password);


// Check if the connection is successful

if (connection != null) {

System.out.println("Connected to the database!");

// You can perform database operations here

// Close the connection when done

connection.close();

} else {

System.out.println("Failed to connect to the database!");

} catch (ClassNotFoundException e) {

System.err.println("JDBC Driver not found: " + e.getMessage());

} catch (SQLException e) {

System.err.println("Database connection error: " + e.getMessage());

2. Implementation of airline reservation system using JDBC.


Code
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Scanner;

public class AirlineReservationSystem {

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/airline_reservation";

private static final String DB_USER = "your_username";

private static final String DB_PASSWORD = "your_password";

public static void main(String[] args) {

try {

Connection connection = DriverManager.getConnection(JDBC_URL, DB_USER, DB_PASSWORD);

System.out.println("Airline Reservation System");

System.out.println("1. Register");

System.out.println("2. Book a Flight");

System.out.println("3. Exit");

Scanner scanner = new Scanner(System.in);

int choice = scanner.nextInt();

switch (choice) {

case 1:

registerUser(connection, scanner);

break;
case 2:

bookFlight(connection, scanner);

break;

case 3:

System.exit(0);

default:

System.out.println("Invalid choice.");

connection.close();

} catch (SQLException e) {

e.printStackTrace();

private static void registerUser(Connection connection, Scanner scanner) throws SQLException {

System.out.println("Enter username: ");

String username = scanner.next();

System.out.println("Enter password: ");

String password = scanner.next();

String sql = "INSERT INTO users (username, password) VALUES (?, ?)";

PreparedStatement preparedStatement = connection.prepareStatement(sql);

preparedStatement.setString(1, username);

preparedStatement.setString(2, password);
int rowsInserted = preparedStatement.executeUpdate();

if (rowsInserted > 0) {

System.out.println("User registered successfully.");

} else {

System.out.println("Failed to register user.");

private static void bookFlight(Connection connection, Scanner scanner) throws SQLException {

System.out.println("Enter your username: ");

String username = scanner.next();

System.out.println("Available Flights:");

String sql = "SELECT * FROM flights WHERE available_seats > 0";

PreparedStatement preparedStatement = connection.prepareStatement(sql);

ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {

int flightId = resultSet.getInt("flight_id");

String flightName = resultSet.getString("flight_name");

System.out.println(flightId + ". " + flightName);

System.out.println("Enter flight ID to book: ");


int selectedFlightId = scanner.nextInt();

// Perform booking logic here, update the available seats in the 'flights' table

// This is a simplified example and doesn't include the complete booking process.

// You should implement a proper booking system with transaction handling.

System.out.println("Flight booked successfully!");

3. Write a JDBC program to retrieve the student details from the


database.
Code
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class RetrieveStudentDetails {

public static void main(String[] args) {

// Database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";

String username = "your_username";

String password = "your_password";


// SQL query to retrieve student details

String sqlQuery = "SELECT * FROM students";

try (

// Establish a database connection

Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

// Create a prepared statement for the SQL query

PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);

// Execute the query and retrieve the results

ResultSet resultSet = preparedStatement.executeQuery()

){

// Iterate through the result set and display student details

while (resultSet.next()) {

int studentId = resultSet.getInt("student_id");

String firstName = resultSet.getString("first_name");

String lastName = resultSet.getString("last_name");

int age = resultSet.getInt("age");

System.out.println("Student ID: " + studentId);

System.out.println("First Name: " + firstName);

System.out.println("Last Name: " + lastName);

System.out.println("Age: " + age);


System.out.println();

} catch (SQLException e) {

e.printStackTrace();

4. Implement java program to retrieve contents of a table using JDBC


connection.
Code
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class RetrieveTableContents {

public static void main(String[] args) {

// Database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";

String username = "your_username";

String password = "your_password";

// SQL query to retrieve all records from the 'students' table


String sqlQuery = "SELECT * FROM students";

try (

// Establish a database connection

Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

// Create a prepared statement for the SQL query

PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);

// Execute the query and retrieve the results

ResultSet resultSet = preparedStatement.executeQuery()

){

// Iterate through the result set and display table contents

while (resultSet.next()) {

int studentId = resultSet.getInt("student_id");

String firstName = resultSet.getString("first_name");

String lastName = resultSet.getString("last_name");

int age = resultSet.getInt("age");

System.out.println("Student ID: " + studentId);

System.out.println("First Name: " + firstName);

System.out.println("Last Name: " + lastName);

System.out.println("Age: " + age);

System.out.println();

}
} catch (SQLException e) {

e.printStackTrace();

5. Write JDBC program to insert records to a table using JDBC


connection.
Code
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class InsertRecords {

public static void main(String[] args) {

// Database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";

String username = "your_username";

String password = "your_password";

// SQL query to insert a new student record

String sqlQuery = "INSERT INTO students (first_name, last_name, age) VALUES (?, ?, ?)";

try (
// Establish a database connection

Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

// Create a prepared statement for the SQL query

PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)

){

// Set values for the placeholders in the SQL query

preparedStatement.setString(1, "John");

preparedStatement.setString(2, "Doe");

preparedStatement.setInt(3, 25);

// Execute the query to insert the record

int rowsInserted = preparedStatement.executeUpdate();

if (rowsInserted > 0) {

System.out.println("Record inserted successfully.");

} else {

System.out.println("Failed to insert record.");

} catch (SQLException e) {

e.printStackTrace();

}
6. Write JDBC program to update contents of a library management
system using JDBC connection.
Code
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class UpdateLibraryContents {

public static void main(String[] args) {

// Database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/library_db";

String username = "your_username";

String password = "your_password";

// SQL query to update book availability by book ID

String sqlQuery = "UPDATE library_books SET is_available = ? WHERE book_id = ?";

try (

// Establish a database connection

Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

// Create a prepared statement for the SQL query

PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)

){
// Set new values for book availability and book ID

boolean isAvailable = false; // Change availability status as needed

int bookIdToUpdate = 1; // Replace with the actual book ID

preparedStatement.setBoolean(1, isAvailable);

preparedStatement.setInt(2, bookIdToUpdate);

// Execute the query to update book availability

int rowsUpdated = preparedStatement.executeUpdate();

if (rowsUpdated > 0) {

System.out.println("Book availability updated successfully.");

} else {

System.out.println("Failed to update book availability.");

} catch (SQLException e) {

e.printStackTrace();

7. Write a simple application program to establish JDBC query


execution using PreparedStatement.
Code
import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class JDBCPreparedStatementDemo {

public static void main(String[] args) {

// Database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";

String username = "your_username";

String password = "your_password";

try (

// Establish a database connection

Connection connection = DriverManager.getConnection(jdbcUrl, username, password)

){

// Create a SQL query with a prepared statement

String sqlQuery = "SELECT * FROM students WHERE age > ?";

PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);

// Set parameter values for the prepared statement

int minAge = 18;

preparedStatement.setInt(1, minAge);

// Execute the query and retrieve the results


ResultSet resultSet = preparedStatement.executeQuery();

// Process the results

while (resultSet.next()) {

int studentId = resultSet.getInt("student_id");

String firstName = resultSet.getString("first_name");

String lastName = resultSet.getString("last_name");

int age = resultSet.getInt("age");

System.out.println("Student ID: " + studentId);

System.out.println("First Name: " + firstName);

System.out.println("Last Name: " + lastName);

System.out.println("Age: " + age);

System.out.println();

} catch (SQLException e) {

e.printStackTrace();

8. Write a simple application program to establish JDBC query


execution using ResultSet executeQurey.
Code
import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class JDBCResultSetDemo {

public static void main(String[] args) {

// Database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";

String username = "your_username";

String password = "your_password";

try (

// Establish a database connection

Connection connection = DriverManager.getConnection(jdbcUrl, username, password)

){

// Create a SQL query

String sqlQuery = "SELECT * FROM students";

// Create a statement to execute the query

Statement statement = connection.createStatement();

// Execute the query and retrieve the results

ResultSet resultSet = statement.executeQuery(sqlQuery);


// Process the results

while (resultSet.next()) {

int studentId = resultSet.getInt("student_id");

String firstName = resultSet.getString("first_name");

String lastName = resultSet.getString("last_name");

int age = resultSet.getInt("age");

System.out.println("Student ID: " + studentId);

System.out.println("First Name: " + firstName);

System.out.println("Last Name: " + lastName);

System.out.println("Age: " + age);

System.out.println();

} catch (SQLException e) {

e.printStackTrace();

9. Implement java program Query data from MYSQL using JDBC with
simple SQL statement.
Code
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Statement;

public class MySQLJDBCQueryDemo {

public static void main(String[] args) {

// Database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";

String username = "your_username";

String password = "your_password";

try (

// Establish a database connection

Connection connection = DriverManager.getConnection(jdbcUrl, username, password)

){

// Create a SQL SELECT statement

String sqlQuery = "SELECT * FROM students";

// Create a statement to execute the query

Statement statement = connection.createStatement();

// Execute the query and retrieve the results

ResultSet resultSet = statement.executeQuery(sqlQuery);

// Process the results

while (resultSet.next()) {
int studentId = resultSet.getInt("student_id");

String firstName = resultSet.getString("first_name");

String lastName = resultSet.getString("last_name");

int age = resultSet.getInt("age");

System.out.println("Student ID: " + studentId);

System.out.println("First Name: " + firstName);

System.out.println("Last Name: " + lastName);

System.out.println("Age: " + age);

System.out.println();

} catch (SQLException e) {

e.printStackTrace();

10. Implementation of airline Library maintenance system using JDBC.


Code
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Scanner;
public class AirlineLibrarySystem {

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/airline_library";

private static final String DB_USER = "your_username";

private static final String DB_PASSWORD = "your_password";

public static void main(String[] args) {

try {

Connection connection = DriverManager.getConnection(JDBC_URL, DB_USER, DB_PASSWORD);

System.out.println("Airline Library System");

System.out.println("1. Add a Book");

System.out.println("2. List Available Books");

System.out.println("3. Borrow a Book");

System.out.println("4. Exit");

Scanner scanner = new Scanner(System.in);

int choice = scanner.nextInt();

switch (choice) {

case 1:

addBook(connection, scanner);

break;

case 2:

listAvailableBooks(connection);
break;

case 3:

borrowBook(connection, scanner);

break;

case 4:

System.exit(0);

default:

System.out.println("Invalid choice.");

connection.close();

} catch (SQLException e) {

e.printStackTrace();

private static void addBook(Connection connection, Scanner scanner) throws SQLException {

System.out.println("Enter book title: ");

String title = scanner.next();

System.out.println("Enter author: ");

String author = scanner.next();

System.out.println("Enter the number of copies available: ");

int copiesAvailable = scanner.nextInt();

String sql = "INSERT INTO books (title, author, copies_available) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);

preparedStatement.setString(1, title);

preparedStatement.setString(2, author);

preparedStatement.setInt(3, copiesAvailable);

int rowsInserted = preparedStatement.executeUpdate();

if (rowsInserted > 0) {

System.out.println("Book added to the library.");

} else {

System.out.println("Failed to add the book.");

private static void listAvailableBooks(Connection connection) throws SQLException {

String sql = "SELECT * FROM books WHERE copies_available > 0";

PreparedStatement preparedStatement = connection.prepareStatement(sql);

ResultSet resultSet = preparedStatement.executeQuery();

System.out.println("Available Books:");

while (resultSet.next()) {

int bookId = resultSet.getInt("book_id");

String title = resultSet.getString("title");

String author = resultSet.getString("author");

int copiesAvailable = resultSet.getInt("copies_available");


System.out.println(bookId + ". " + title + " by " + author + " (Copies Available: " + copiesAvailable +
")");

private static void borrowBook(Connection connection, Scanner scanner) throws SQLException {

System.out.println("Enter your name: ");

String passengerName = scanner.next();

System.out.println("Enter the book ID you want to borrow: ");

int bookId = scanner.nextInt();

// Check if the book is available

String availabilityCheckSql = "SELECT copies_available FROM books WHERE book_id = ?";

PreparedStatement availabilityCheckStatement =
connection.prepareStatement(availabilityCheckSql);

availabilityCheckStatement.setInt(1, bookId);

ResultSet availabilityResultSet = availabilityCheckStatement.executeQuery();

if (availabilityResultSet.next()) {

int copiesAvailable = availabilityResultSet.getInt("copies_available");

if (copiesAvailable > 0) {

// Borrow the book

String borrowSql = "INSERT INTO passengers (name, book_id) VALUES (?, ?)";

PreparedStatement borrowStatement = connection.prepareStatement(borrowSql);

borrowStatement.setString(1, passengerName);

borrowStatement.setInt(2, bookId);
int rowsUpdated = borrowStatement.executeUpdate();

if (rowsUpdated > 0) {

System.out.println("Book borrowed successfully.");

// Update the copies available in the books table

String updateCopiesSql = "UPDATE books SET copies_available = ? WHERE book_id = ?";

PreparedStatement updateCopiesStatement =
connection.prepareStatement(updateCopiesSql);

updateCopiesStatement.setInt(1, copiesAvailable - 1);

updateCopiesStatement.setInt(2, bookId);

updateCopiesStatement.executeUpdate();

} else {

System.out.println("Failed to borrow the book.");

} else {

System.out.println("Sorry, the book is not available.");

} else {

System.out.println("Book not found.");

You might also like