0% found this document useful (0 votes)
26 views20 pages

Practical Assignment 3 Java-Ii

The document contains a series of Java programming assignments focused on database operations using MySQL. It includes code snippets for creating and managing employee and product databases, displaying metadata, and handling teacher records. Each assignment demonstrates the use of JDBC for database connectivity and Swing for user interfaces.

Uploaded by

Shruti Kondekar
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)
26 views20 pages

Practical Assignment 3 Java-Ii

The document contains a series of Java programming assignments focused on database operations using MySQL. It includes code snippets for creating and managing employee and product databases, displaying metadata, and handling teacher records. Each assignment demonstrates the use of JDBC for database connectivity and Swing for user interfaces.

Uploaded by

Shruti Kondekar
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/ 20

PRACTICAL ASSIGNMENT-3 JAVA-II

Q.1.Write a Java program to accept the details of Employee (Eno,


EName, Designation, Salary) from a user and store it into the database.
(Use Swing).

ANS.

Mysql> create database employeedb;

Mysql> use database employeedb;

Mysql> create table employee;

Java Code,

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.sql.*;

public class EmployeeForm extends JFrame

JTextField enoField = new JTextField(), enameField = new JTextField(),


designationField = new JTextField(), salaryField = new JTextField();

JButton saveButton = new JButton("Save");

public EmployeeForm()

setTitle("Employee Form");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(5, 2));

add(new JLabel("Emp No:"));

add(enoField);

add(new JLabel("Name:"));

add(enameField);

add(new JLabel("Designation:"));
add(designationField);

add(new JLabel("Salary:"));

add(salaryField);

add(saveButton);

saveButton.addActionListener(e -> saveEmployee());

private void saveEmployee()

String url = "jdbc:mysql://localhost:3306/employeedb";

String username = "root";

String password = "password";

try (Connection conn = DriverManager.getConnection(url, username,


password);

PreparedStatement stmt = conn.prepareStatement("INSERT INTO


employee (eno, ename, designation, salary) VALUES (?, ?, ?, ?)"))

stmt.setInt(1, Integer.parseInt(enoField.getText()));

stmt.setString(2, enameField.getText());

stmt.setString(3, designationField.getText());

stmt.setDouble(4, Double.parseDouble(salaryField.getText()));

stmt.executeUpdate();

JOptionPane.showMessageDialog(this, "Employee saved!");

catch (Exception ex)

JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());

}
public static void main(String[] args)

SwingUtilities.invokeLater(() -> new EmployeeForm().setVisible(true));

For compile and run,

javac -cp .;source\mysql-connector-j-9.2.0.jar EmployeeForm.java

java -cp .;source\mysql-connector-j-9.2.0.jar EmployeeForm

OUTPUT(1) OUTPUT(2)

Q.2.Write a java program for the following:

i. To create a Product(Pid, Pname, Price) table.

ii. Insert at least five records into the table.

iii.Display all the records from a table.

ANS.

Mysql> create database employeedb;

Java Code,

import java.sql.*;

import java.util.Scanner;
public class ProductDatabase {

public static void main(String[] args) {

// Database connection details

String url = "jdbc:mysql://localhost:3306/ProductDB";

String user = "root";

String password = "password";

String createTableQuery = "CREATE TABLE IF NOT EXISTS Product ("

+ "Pid INT PRIMARY KEY, "

+ "Pname VARCHAR(100), "

+ "Price DECIMAL(10, 2))";

String insertQuery = "INSERT INTO Product (Pid, Pname, Price)


VALUES (?, ?, ?)";

String selectQuery = "SELECT * FROM Product";

try (Connection conn = DriverManager.getConnection(url, user,


password);

Statement stmt = conn.createStatement();

Scanner scanner = new Scanner(System.in)) {

// Create Product table

stmt.executeUpdate(createTableQuery);

System.out.println("Product table created successfully.");

// Ask user for product details and insert

PreparedStatement pstmt = conn.prepareStatement(insertQuery);

while (true)
{

System.out.print("Enter Product ID (or 0 to stop): ");

int pid = scanner.nextInt();

if (pid == 0) break;

scanner.nextLine(); // Consume newline left by nextInt()

System.out.print("Enter Product Name: ");

String pname = scanner.nextLine();

System.out.print("Enter Product Price: ");

double price = scanner.nextDouble();

pstmt.setInt(1, pid);

pstmt.setString(2, pname);

pstmt.setBigDecimal(3, new java.math.BigDecimal(price));

pstmt.executeUpdate();

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

// Display all products

ResultSet rs = stmt.executeQuery(selectQuery);

System.out.println("Displaying all products:");

while (rs.next()) {

System.out.println("Pid: " + rs.getInt("Pid")

+ ", Pname: " + rs.getString("Pname")

+ ", Price: " + rs.getDouble("Price"));

} catch (SQLException e) {

e.printStackTrace();

}
INPUT,

Enter Product ID (or 0 to stop): 1

Enter Product Name: laptop

Enter Product Price: 65000

Product inserted successfully.

Enter Product ID (or 0 to stop): 2

Enter Product Name: Smartphone

Enter Product Price: 50000

Product inserted successfully.

Enter Product ID (or 0 to stop): 3

Enter Product Name: Tablet

Enter Product Price: 95000

Product inserted successfully.

Enter Product ID (or 0 to stop): 4

Enter Product Name: Headphones

Enter Product Price: 5000

Product inserted successfully.

Enter Product ID (or 0 to stop): 5

Enter Product Name: Monitor

Enter Product Price: 20000

Product inserted successfully.

Enter Product ID (or 0 to stop): 0

OUTPUT,

Displaying all products:

Pid: 1, Pname: laptop, Price: 65000.0

Pid: 2, Pname: Smartphone, Price: 50000.0

Pid: 3, Pname: Tablet, Price: 95000.0

Pid: 4, Pname: Headphones, Price: 5000.0

Pid: 5, Pname: Monitor, Price: 20000.0


OR

import java.sql.*;

public class ProductDatabase {

public static void main(String[] args) {

// JDBC URL, username, and password

String url = "jdbc:mysql://localhost:3306/ProductDB"; // Replace with


your database URL

String user = "root"; // Replace with your username

String password = "Password"; // Replace with your password

// SQL queries to create table, insert records, and display records

String createTableQuery = "CREATE TABLE IF NOT EXISTS Product ("

+ "Pid INT PRIMARY KEY, "

+ "Pname VARCHAR(100), "

+ "Price DECIMAL(10, 2))";

String insertQuery = "INSERT INTO Product (Pid, Pname, Price)


VALUES (?, ?, ?)";

String selectQuery = "SELECT * FROM Product";

// Establishing connection, creating table, and inserting data

try (Connection conn = DriverManager.getConnection(url, user,


password);

Statement stmt = conn.createStatement()) {

// Create Product table

stmt.executeUpdate(createTableQuery);

System.out.println("Product table created successfully.");

// Insert sample records into Product table


try (PreparedStatement pstmt =
conn.prepareStatement(insertQuery)) {

pstmt.setInt(1, 1);

pstmt.setString(2, "Laptop");

pstmt.setBigDecimal(3, new java.math.BigDecimal(65000));

pstmt.executeUpdate();

pstmt.setInt(1, 2);

pstmt.setString(2, "Smartphone");

pstmt.setBigDecimal(3, new java.math.BigDecimal(50000));

pstmt.executeUpdate();

pstmt.setInt(1, 3);

pstmt.setString(2, "Tablet");

pstmt.setBigDecimal(3, new java.math.BigDecimal(95000));

pstmt.executeUpdate();

pstmt.setInt(1, 4);

pstmt.setString(2, "Headphones");

pstmt.setBigDecimal(3, new java.math.BigDecimal(5000));

pstmt.executeUpdate();

pstmt.setInt(1, 5);

pstmt.setString(2, "Monitor");

pstmt.setBigDecimal(3, new java.math.BigDecimal(20000));

pstmt.executeUpdate();

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


// Display all records from Product table

try (ResultSet rs = stmt.executeQuery(selectQuery)) {

System.out.println("Displaying all records from Product table:");

while (rs.next()) {

int pid = rs.getInt("Pid");

String pname = rs.getString("Pname");

double price = rs.getDouble("Price");

System.out.println("Pid: " + pid + ", Pname: " + pname + ",


Price: " + price);

} catch (SQLException e) {

e.printStackTrace();

OUTPUT,

Product table created successfully.

Records inserted successfully.

Displaying all records from Product table:

Pid: 1, Pname: laptop, Price: 65000.0

Pid: 2, Pname: Smartphone, Price: 50000.0

Pid: 3, Pname: Tablet, Price: 95000.0

Pid: 4, Pname: Headphones, Price: 5000.0

Pid: 5, Pname: Monitor, Price: 20000.0


Q.3. write a java program to display information about all columns in
the DONAR table usng ResultSetMetaData.

ANS.

mysql> create database DonarDB;

mysql> use DONARDB;

mysql> CREATE TABLE DONAR (

-> DonarID INT PRIMARY KEY,

-> DonarName VARCHAR(100),

-> BloodType VARCHAR(5)

-> );

Java Code,

import java.sql.*;

public class DonarTableMetadata {

public static void main(String[] args) {

// Database connection details

String url = "jdbc:mysql://localhost:3306/DonarDB"; // Replace with


your database name

String user = "root"; // Replace with your username

String password = "password"; // Replace with your password

String selectQuery = "SELECT * FROM DONAR"; // Query to get all


data from the DONAR table

try (Connection conn = DriverManager.getConnection(url, user,


password);

Statement stmt = conn.createStatement();


ResultSet rs = stmt.executeQuery(selectQuery)) {

// Get ResultSetMetaData

ResultSetMetaData metaData = rs.getMetaData();

// Get the number of columns in the ResultSet

int columnCount = metaData.getColumnCount();

System.out.println("Information about columns in the DONAR


table:");

// Loop through all columns and display details

for (int i = 1; i <= columnCount; i++) {

String columnName = metaData.getColumnName(i);

String columnType = metaData.getColumnTypeName(i);

int columnSize = metaData.getColumnDisplaySize(i);

System.out.println("Column " + i + ":");

System.out.println(" Name: " + columnName);

System.out.println(" Type: " + columnType);

System.out.println(" Size: " + columnSize);

System.out.println("-----------------------------------");

} catch (SQLException e) {

e.printStackTrace();

}
OUTPUT,

Information about columns in the DONAR table:

Column 1:

Name: DonarID

Type: INT

Size: 10

-----------------------------------

Column 2:

Name: DonarName

Type: VARCHAR

Size: 100

-----------------------------------

Column 3:

Name: BloodType

Type: VARCHAR

Size: 5

Q.4. Write a java program to display information about the database


and list all the tables in the database. (use DatabaseMetaData).

ANS.

mysql> create database DatabaseDB;

Java Code,

import java.sql.*;

public class DatabaseInfo {

public static void main(String[] args) {

// Database connection details


String url = "jdbc:mysql://localhost:3306/DatabaseDB"; // Replace
with your database name

String user = "root"; // Replace with your username

String password = "password"; // Replace with your password

try (Connection conn = DriverManager.getConnection(url, user,


password)) {

// Get DatabaseMetaData

DatabaseMetaData metaData = conn.getMetaData();

// Display information about the database

System.out.println("Database Product Name: " +


metaData.getDatabaseProductName());

System.out.println("Database Product Version: " +


metaData.getDatabaseProductVersion());

System.out.println("Driver Name: " + metaData.getDriverName());

System.out.println("Driver Version: " + metaData.getDriverVersion());

System.out.println("URL: " + metaData.getURL());

System.out.println("User: " + metaData.getUserName());

// Get all tables from the database

System.out.println("\nList of Tables in the Database:");

ResultSet tables = metaData.getTables(null, null, "%", new


String[]{"TABLE"});

while (tables.next()) {

System.out.println(tables.getString("TABLE_NAME"));

} catch (SQLException e) {

e.printStackTrace();

}
OUTPUT,

Database Product Name: MySQL

Database Product Version: 8.0.41

Driver Name: MySQL Connector/J

Driver Version: mysql-connector-j-9.2.0 (Revision:


a3909bfeb62d5a517ab444bb88ba7ecf26100297)

URL: jdbc:mysql://localhost:3306/DatabaseDB

User: root@localhost

List of Tables in the Database:

employee

users

donar

employee

product

Q.5. Write a java program to accept the details of Teacher(TNo, TName,


Subject), Insert at least 5 Records into Teacher Table and display the
details of Teacher who is teaching "JAVA" Subject. (Use
PreparedStatement Interface)

ANS,

mysql> create database TeacherDB;

mysql> use TeacherDB;

mysql> CREATE TABLE Teacher (

-> TNo INT PRIMARY KEY,

-> TName VARCHAR(50),

-> Subject VARCHAR(50)

-> );
Java Code,

import java.sql.*;

public class TeacherDetails {

public static void main(String[] args) {

// Database URL, username, and password

String url = "jdbc:mysql://localhost:3306/TeacherDB";

String username = "root";

String password = "password";

// SQL queries

String insertQuery = "INSERT INTO Teacher (TNo, TName, Subject)


VALUES (?, ?, ?)";

String selectQuery = "SELECT * FROM Teacher WHERE Subject = ?";

// Establishing the database connection

try (Connection connection = DriverManager.getConnection(url,


username, password)) {

// Inserting records into the Teacher table

try (PreparedStatement insertStmt =


connection.prepareStatement(insertQuery)) {

// Inserting 5 records

insertStmt.setInt(1, 1);

insertStmt.setString(2, "Mahadik Madam");

insertStmt.setString(3, "JAVA");

insertStmt.executeUpdate();

insertStmt.setInt(1, 2);

insertStmt.setString(2, "Wanave Madam");


insertStmt.setString(3, "Python");

insertStmt.executeUpdate();

insertStmt.setInt(1, 3);

insertStmt.setString(2, "Bhong Madam");

insertStmt.setString(3, "OS");

insertStmt.executeUpdate();

insertStmt.setInt(1, 4);

insertStmt.setString(2, "Shaikh Sir");

insertStmt.setString(3, "DA");

insertStmt.executeUpdate();

insertStmt.setInt(1, 5);

insertStmt.setString(2, "Tamboli Sir");

insertStmt.setString(3, "STT");

insertStmt.executeUpdate();

// Displaying details of teachers who teach "JAVA"

try (PreparedStatement selectStmt =


connection.prepareStatement(selectQuery)) {

selectStmt.setString(1, "JAVA");

ResultSet resultSet = selectStmt.executeQuery();

System.out.println("Teachers teaching JAVA:");

while (resultSet.next()) {

int tNo = resultSet.getInt("TNo");

String tName = resultSet.getString("TName");


String subject = resultSet.getString("Subject");

System.out.println("TNo: " + tNo + ", TName: " + tName + ",


Subject: " + subject);

} catch (SQLException e) {

e.printStackTrace();

OUTPUT,

Teachers teaching JAVA:

TNo: 1, TName: Mahadik Madam, Subject: JAVA

OR

import java.sql.*;

import java.util.Scanner;

public class TeacherDetails {

public static void main(String[] args) {

// Database URL, username, and password

String url = "jdbc:mysql://localhost:3306/TeacherDB";

String username = "root";

String password = "password";

// SQL queries

String insertQuery = "INSERT INTO Teacher (TNo, TName, Subject)


VALUES (?, ?, ?)";

String selectQuery = "SELECT * FROM Teacher WHERE Subject = ?";


// Scanner object for taking user input

Scanner scanner = new Scanner(System.in);

// Establishing the database connection

try (Connection connection = DriverManager.getConnection(url,


username, password)) {

// Asking user to input teacher details

for (int i = 0; i < 5; i++) {

System.out.println("Enter details for Teacher " + (i + 1) + ":");

// Input Teacher Number (TNo) as String now

System.out.print("Enter Teacher No (TNo): ");

String tNo = scanner.nextLine(); // Changed to nextLine for non-


integer input

// Input Teacher Name

System.out.print("Enter Teacher Name (TName): ");

String tName = scanner.nextLine();

// Input Subject

System.out.print("Enter Subject: ");

String subject = scanner.nextLine();

// Inserting the teacher details into the Teacher table using


PreparedStatement

try (PreparedStatement insertStmt =


connection.prepareStatement(insertQuery)) {

insertStmt.setString(1, tNo); // TNo is now a String

insertStmt.setString(2, tName);

insertStmt.setString(3, subject);

insertStmt.executeUpdate();

System.out.println("Teacher details inserted successfully!\n");

}
// Displaying details of teachers who teach "JAVA"

try (PreparedStatement selectStmt =


connection.prepareStatement(selectQuery)) {

selectStmt.setString(1, "JAVA");

ResultSet resultSet = selectStmt.executeQuery();

System.out.println("Teachers teaching JAVA:");

while (resultSet.next()) {

String tNo = resultSet.getString("TNo");

String tName = resultSet.getString("TName");

String subject = resultSet.getString("Subject");

System.out.println("TNo: " + tNo + ", TName: " + tName + ",


Subject: " + subject);

} catch (SQLException e) {

e.printStackTrace();

} finally {

scanner.close();

INPUT,

Enter details for Teacher 1:

Enter Teacher No (TNo): 101

Enter Teacher Name (TName): Mahadik Madam

Enter Subject: JAVA

Teacher details inserted successfully!


Enter details for Teacher 2:

Enter Teacher No (TNo): 102

Enter Teacher Name (TName): Wanave Madam

Enter Subject: Python

Teacher details inserted successfully!

Enter details for Teacher 3:

Enter Teacher No (TNo): 103

Enter Teacher Name (TName): Bhong Madam

Enter Subject: OS

Teacher details inserted successfully!

Enter details for Teacher 4:

Enter Teacher No (TNo): 104

Enter Teacher Name (TName): Shaikh Sir

Enter Subject: DA

Teacher details inserted successfully!

Enter details for Teacher 5:

Enter Teacher No (TNo): 105

Enter Teacher Name (TName): Tamboli Sir

Enter Subject: STT

Teacher details inserted successfully!

OUTPUT,

Teachers teaching JAVA:

TNo: 101, TName: Mahadik Madam, Subject: JAVA

You might also like