Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

JAVA-LAB-4

The document outlines a lab assignment involving database operations using JDBC. It includes creating a database and a user table, inserting user data through a GUI, and performing CRUD operations in a console application. Additionally, it describes operations on a student database, including inserting, updating, and deleting records while displaying the results at each step.

Uploaded by

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

JAVA-LAB-4

The document outlines a lab assignment involving database operations using JDBC. It includes creating a database and a user table, inserting user data through a GUI, and performing CRUD operations in a console application. Additionally, it describes operations on a student database, including inserting, updating, and deleting records while displaying the results at each step.

Uploaded by

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

LAB 4:

Part 1: Database
1. Create a database and name it ‘db_test’. Open the database and create table ‘User’ with column
‘id’,’name’,’age’, ‘phone_number’, ‘address. ‘Id’ and ‘age’ should be of integer data-type and
other of varchar.

2. Write an insert query to insert your details into database.


3. Write an insert query to insert data into database by reading values from GUI.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class InsertDataGUI extends JFrame {


// Database connection details for Windows Authentication
private static final String DB_URL = "jdbc:sqlserver://DESKTOP-
GQVIKI5:1433;databaseName=db_test;integratedSecurity=true;";

// GUI Components
private JTextField nameField, ageField, phoneField, addressField;
private JButton submitButton;

public InsertDataGUI() {
// Set up the JFrame
setTitle("Insert User Data");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2, 10, 10));

// Add form fields


add(new JLabel("Name:"));
nameField = new JTextField();
add(nameField);

add(new JLabel("Age:"));
ageField = new JTextField();
add(ageField);

add(new JLabel("Phone Number:"));


phoneField = new JTextField();
add(phoneField);

add(new JLabel("Address:"));
addressField = new JTextField();
add(addressField);
// Add Submit button
submitButton = new JButton("Submit");
add(submitButton);

// Add action listener for the button


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
insertDataIntoDatabase();
}
});

// Make the GUI visible


setVisible(true);
}

// Method to insert data into the database


private void insertDataIntoDatabase() {
String name = nameField.getText();
int age = Integer.parseInt(ageField.getText());
String phone = phoneField.getText();
String address = addressField.getText();

String insertSQL = "INSERT INTO [User] (name, age, phone_number, address) VALUES (?, ?, ?, ?)";

try (Connection connection = DriverManager.getConnection(DB_URL);


PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {

// Set parameters
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.setString(3, phone);
preparedStatement.setString(4, address);

// Execute the insert


int rowsAffected = preparedStatement.executeUpdate();
JOptionPane.showMessageDialog(this, rowsAffected + " row(s) inserted successfully!");

// Clear the fields


nameField.setText("");
ageField.setText("");
phoneField.setText("");
addressField.setText("");
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Error: " + e.getMessage(), "Database Error",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}

// Main method to run the program


public static void main(String[] args) {
// Run the InsertDataGUI constructor to display the GUI
SwingUtilities.invokeLater(() -> new InsertDataGUI());
}
}
4. Write query to fetch all data from database.

Part 2:
1. Create a class named “DatabaseCRUD.java” (not compulsory). Write two methods named
“insertIntoDatabase” and “getFromDatabase” to insert into database and fetch from database.
Set connection strings as below: String dbURL = "jdbc:mysql://localhost:3306/test_db"; String
username = "root"; String password = "YOURPASSWORD";
import java.sql.*;
import java.util.Scanner;

public class DatabaseCRUD {


private static final String DB_URL = "jdbc:sqlserver://DESKTOP-GQVIKI5:1433;"
+ "databaseName=db_test;"
+ "integratedSecurity=true;"
+ "encrypt=true;"
+ "trustServerCertificate=true;";

private final Scanner scanner;

public DatabaseCRUD() {
this.scanner = new Scanner(System.in);
}

private Connection getConnection() throws SQLException {


return DriverManager.getConnection(DB_URL);
}

private void displayMenu() {


System.out.println("\n=== Database Operations ===");
System.out.println("1. Insert new user");
System.out.println("2. View all users");
System.out.println("3. Update user");
System.out.println("4. Delete user");
System.out.println("5. Exit");
System.out.print("Choose an option (1-5): ");
}

private String readString(String prompt) {


System.out.print(prompt);
return scanner.nextLine().trim();
}

private int readInt(String prompt) {


while (true) {
try {
System.out.print(prompt);
int value = Integer.parseInt(scanner.nextLine().trim());
if (value < 0) {
System.out.println("Please enter a positive number.");
continue;
}
return value;
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number.");
}
}
}

public void insertIntoDatabase() {


try (Connection connection = getConnection()) {
String name = readString("Enter name: ");
if (name.isEmpty()) {
System.out.println("Name cannot be empty.");
return;
}

int age = readInt("Enter age: ");


String phoneNumber = readString("Enter phone number: ");
String address = readString("Enter address: ");

String sql = "INSERT INTO [User] (name, age, phone_number, address) VALUES (?, ?, ?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.setString(3, phoneNumber);
preparedStatement.setString(4, address);

int rowsAffected = preparedStatement.executeUpdate();


System.out.println("\nSuccess! " + rowsAffected + " row(s) inserted.");
}
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
}
}

public void updateUser() {


try (Connection connection = getConnection()) {
// First show all users so user can choose which to update
getFromDatabase();

int id = readInt("\nEnter the ID of the user to update: ");

// Check if user exists


String checkSql = "SELECT * FROM [User] WHERE id = ?";
try (PreparedStatement checkStmt = connection.prepareStatement(checkSql)) {
checkStmt.setInt(1, id);
ResultSet rs = checkStmt.executeQuery();
if (!rs.next()) {
System.out.println("No user found with ID: " + id);
return;
}
}

// Get new values


System.out.println("Enter new values (press Enter to keep current value):");
String name = readString("Enter new name: ");
String ageStr = readString("Enter new age: ");
String phoneNumber = readString("Enter new phone number: ");
String address = readString("Enter new address: ");

StringBuilder sql = new StringBuilder("UPDATE [User] SET ");


boolean needsComma = false;

if (!name.isEmpty()) {
sql.append("name = ?");
needsComma = true;
}
if (!ageStr.isEmpty()) {
if (needsComma) sql.append(", ");
sql.append("age = ?");
needsComma = true;
}
if (!phoneNumber.isEmpty()) {
if (needsComma) sql.append(", ");
sql.append("phone_number = ?");
needsComma = true;
}
if (!address.isEmpty()) {
if (needsComma) sql.append(", ");
sql.append("address = ?");
}
sql.append(" WHERE id = ?");

try (PreparedStatement preparedStatement = connection.prepareStatement(sql.toString())) {


int parameterIndex = 1;
if (!name.isEmpty()) preparedStatement.setString(parameterIndex++, name);
if (!ageStr.isEmpty()) preparedStatement.setInt(parameterIndex++, Integer.parseInt(ageStr));
if (!phoneNumber.isEmpty()) preparedStatement.setString(parameterIndex++, phoneNumber);
if (!address.isEmpty()) preparedStatement.setString(parameterIndex++, address);
preparedStatement.setInt(parameterIndex, id);

int rowsAffected = preparedStatement.executeUpdate();


System.out.println("\nSuccess! " + rowsAffected + " row(s) updated.");
}
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
} catch (NumberFormatException e) {
System.err.println("Invalid age format entered.");
}
}

public void deleteUser() {


try (Connection connection = getConnection()) {
// First show all users so user can choose which to delete
getFromDatabase();

int id = readInt("\nEnter the ID of the user to delete: ");

String sql = "DELETE FROM [User] WHERE id = ?";


try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setInt(1, id);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("\nSuccess! User with ID " + id + " has been deleted.");
} else {
System.out.println("No user found with ID: " + id);
}
}
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
}
}

public void getFromDatabase() {


try (Connection connection = getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM [User]")) {

boolean hasData = false;


System.out.println("\n=== User Records ===");

while (resultSet.next()) {
hasData = true;
System.out.println("\nID: " + resultSet.getInt("id"));
System.out.println("Name: " + resultSet.getString("name"));
System.out.println("Age: " + resultSet.getInt("age"));
System.out.println("Phone: " + resultSet.getString("phone_number"));
System.out.println("Address: " + resultSet.getString("address"));
System.out.println("-----------------------------");
}

if (!hasData) {
System.out.println("No records found in the database.");
}
} catch (SQLException e) {
System.err.println("Error retrieving data: " + e.getMessage());
}
}

public void run() {


while (true) {
try {
displayMenu();
String input = scanner.nextLine().trim();
int choice = Integer.parseInt(input);

switch (choice) {
case 1:
insertIntoDatabase();
break;
case 2:
getFromDatabase();
break;
case 3:
updateUser();
break;
case 4:
deleteUser();
break;
case 5:
System.out.println("Exiting program. Goodbye!");
scanner.close();
return;
default:
System.out.println("Invalid option. Please choose 1-5.");
}
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number.");
}
}
}

public static void main(String[] args) {


DatabaseCRUD databaseCRUD = new DatabaseCRUD();
databaseCRUD.run();
}
}
2. Assume database name as “College” and table name “Sudent”. A table has student has the field
(s_id, name, address, gender, program). Write a JDBC program to insert record (1,
Sam,Kathmandu,male,CSIT) into database. After insertion display the data into console. Update
program from CSIT to BBA. Again display the record. And at last delete the information where
id=1 and again display the information.
import java.sql.*;

public class StudentDatabaseOperations {


private static final String DB_URL = "jdbc:sqlserver://DESKTOP-GQVIKI5:1433;" +
"databaseName=db_test;" +
"integratedSecurity=true;" +
"encrypt=true;" +
"trustServerCertificate=true;";

public static void main(String[] args) {


try {
// Load the JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Establish connection
try (Connection conn = DriverManager.getConnection(DB_URL)) {
System.out.println("Database connected successfully!");

// Create table if it doesn't exist


createTable(conn);

// 1. Insert Record
String insertSQL = "INSERT INTO Student (s_id, name, address, gender, program) VALUES
(?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
pstmt.setInt(1, 1);
pstmt.setString(2, "Sam");
pstmt.setString(3, "Kathmandu");
pstmt.setString(4, "male");
pstmt.setString(5, "CSIT");
pstmt.executeUpdate();
System.out.println("\nRecord inserted successfully!");
}

// Display after insertion


displayRecords(conn);

// 2. Update Record
String updateSQL = "UPDATE Student SET program = ? WHERE s_id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(updateSQL)) {
pstmt.setString(1, "BBA");
pstmt.setInt(2, 1);
pstmt.executeUpdate();
System.out.println("\nRecord updated successfully!");
}

// Display after update


displayRecords(conn);

// 3. Delete Record
String deleteSQL = "DELETE FROM Student WHERE s_id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(deleteSQL)) {
pstmt.setInt(1, 1);
pstmt.executeUpdate();
System.out.println("\nRecord deleted successfully!");
}

// Display after deletion


displayRecords(conn);
}
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found: " + e.getMessage());
} catch (SQLException e) {
System.out.println("Database error occurred: " + e.getMessage());
}
}

private static void createTable(Connection conn) throws SQLException {


// First, check if table exists and drop it if it does
try (Statement stmt = conn.createStatement()) {
// In SQL Server, we need to check for table existence before dropping
String checkTable = "IF OBJECT_ID('Student', 'U') IS NOT NULL DROP TABLE Student";
stmt.executeUpdate(checkTable);

// Create the table


String createTableSQL = "CREATE TABLE Student ("
+ "s_id INT PRIMARY KEY,"
+ "name VARCHAR(50) NOT NULL,"
+ "address VARCHAR(100),"
+ "gender VARCHAR(10),"
+ "program VARCHAR(50)"
+ ")";
stmt.executeUpdate(createTableSQL);
System.out.println("Table created successfully!");
}
}

private static void displayRecords(Connection conn) throws SQLException {


String selectSQL = "SELECT * FROM Student";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(selectSQL)) {

System.out.println("\nCurrent Student Records:");


System.out.println("------------------------");
if (!rs.isBeforeFirst()) {
System.out.println("No records found in the database.");
return;
}

while (rs.next()) {
System.out.printf("ID: %d, Name: %s, Address: %s, Gender: %s, Program: %s%n",
rs.getInt("s_id"),
rs.getString("name"),
rs.getString("address"),
rs.getString("gender"),
rs.getString("program")
);
}
System.out.println("------------------------");
}
}
}

You might also like