JDBC Slips Answer
JDBC Slips Answer
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)
*/
import java.sql.*;
pstmt.close();
conn.close();
}
ResultSet rs = pstmt.executeQuery();
rs.close();
pstmt.close();
conn.close();
}
import java.sql.*;
public class DatabaseInfo {
try {
// Establish the database connection
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close(); // Close the connection
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
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).
*/
package com.sqltest;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
try {
// Establish connection to the database
conn = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
// Handle database errors
JOptionPane.showMessageDialog(null, "Error saving employee details: " + e.getMessage());
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
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.
*/
package com.sqltest;
import java.sql.*;
public class ProductDatabase {
// JDBC URL, username, and password
static final String DB_URL = "jdbc:postgresql://localhost:5432/dpu";
static final String USER = "postgres";
static final String PASS = "postgres";
public static void main(String[] args) {
// Creating Product Table
createProductTable();
// Inserting Product Records
insertProductRecords();
// Displaying Product Records
displayAllProducts();
}
// Method to create Product table
public static void createProductTable() {
Connection conn = null;
Statement stmt = null;
try {
// Establish connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
// SQL query to create Product table
String createTableSQL = "CREATE TABLE IF NOT EXISTS Product (" +
"Pid INT PRIMARY KEY, " +
"Pname VARCHAR(100), " +
"Price DECIMAL(10, 2))";
// Execute the query
stmt.executeUpdate(createTableSQL);
System.out.println("Product table created successfully!");
} catch (SQLException e) {
System.out.println("Error creating table: " + e.getMessage());
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Method to insert records into the Product table
public static void insertProductRecords() {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// Establish connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// SQL query to insert product records
String insertSQL = "INSERT INTO Product (Pid, Pname, Price) VALUES (?, ?, ?)";
// Prepare statement
pstmt = conn.prepareStatement(insertSQL);
// Inserting 5 product records
pstmt.setInt(1, 101); pstmt.setString(2, "Laptop"); pstmt.setDouble(3, 50000.00);
pstmt.executeUpdate();
pstmt.setInt(1, 102); pstmt.setString(2, "Smartphone"); pstmt.setDouble(3, 30000.00);
pstmt.executeUpdate();
pstmt.setInt(1, 103); pstmt.setString(2, "Headphones"); pstmt.setDouble(3, 1500.00);
pstmt.executeUpdate();
pstmt.setInt(1, 104); pstmt.setString(2, "Smartwatch"); pstmt.setDouble(3, 8000.00);
pstmt.executeUpdate();
pstmt.setInt(1, 105); pstmt.setString(2, "Tablet"); pstmt.setDouble(3, 25000.00);
pstmt.executeUpdate();
System.out.println("Product records inserted successfully!");
} catch (SQLException e) {
System.out.println("Error inserting records: " + e.getMessage());
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Method to display all product records
public static void displayAllProducts() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
// SQL query to get all products
String selectSQL = "SELECT * FROM Product";
// Execute query and get result set
rs = stmt.executeQuery(selectSQL);
// Displaying product records
System.out.println("Product Records:");
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) {
System.out.println("Error displaying records: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
Write a java program to display information about all columns in the DONAR table using
ResultSetMetaData.
*/
package com.sqltest;
import java.sql.*;
public class DonarTableMetaData {
// JDBC URL, username, and password
static final String DB_URL = "jdbc:postgresql://localhost:5432/dpu";
static final String USER = "postgres";
static final String PASS = "postgres";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ResultSetMetaData rsMetaData = null;
try {
// Establish connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Create a statement
stmt = conn.createStatement();
// Execute the query to select all data from the DONAR table
rs = stmt.executeQuery("SELECT * FROM DONAR");
// Get ResultSetMetaData object
rsMetaData = rs.getMetaData();
// Get the number of columns in the DONAR table
int columnCount = rsMetaData.getColumnCount();
// Display column information
System.out.println("Column Information for the DONAR Table:");
for (int i = 1; i <= columnCount; i++) {
String columnName = rsMetaData.getColumnName(i);
int columnType = rsMetaData.getColumnType(i);
String columnTypeName = rsMetaData.getColumnTypeName(i);
int columnSize = rsMetaData.getColumnDisplaySize(i);
String nullable = rsMetaData.isNullable(i) == ResultSetMetaData.columnNullable ? "Nullable" : "Not
Nullable";
// Display each column's details
System.out.println("Column " + i + ":");
System.out.println(" Name: " + columnName);
System.out.println(" Type: " + columnTypeName + " (" + columnType + ")");
System.out.println(" Size: " + columnSize);
System.out.println(" Nullable: " + nullable);
System.out.println("----------------------------------");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
Write a Java program to display first record from student table (RNo, SName, Per) onto the
TextField by clicking on button.(Assume Student table is already cerated)
*/
package com.sqltest;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
// Create labels and text fields for displaying the student record
JLabel rnoLabel = new JLabel("Roll No:");
JLabel snameLabel = new JLabel("Student Name:");
JLabel perLabel = new JLabel("Percentage:");
try {
// Establish connection to the database
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Create a statement
stmt = conn.createStatement();
} catch (SQLException e) {
// Handle database errors
JOptionPane.showMessageDialog(null, "Error fetching record: " + e.getMessage());
e.printStackTrace();
} finally {
try {
// Close resources
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
Write a Java Program to create a PROJECT table with field's project_id, Project_name,
Project_description, Project_Status. Insert values in the table. Display all the details of the
PROJECT table in a tabular format on the screen. (using swing).
*/
package com.sqltest;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.table.DefaultTableModel;
// Create the PROJECT table and insert sample data (if not already created)
createAndInsertProjectData();
}
try {
// Establish connection to the database
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Method to load data from the PROJECT table and display it in the JTable
public static void loadProjectData(DefaultTableModel tableModel) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish connection to the database
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
// Iterate through the result set and add rows to the table model
while (rs.next()) {
int projectId = rs.getInt("project_id");
String projectName = rs.getString("project_name");
String projectDescription = rs.getString("project_description");
String projectStatus = rs.getString("project_status");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
Write a Menu Driven program in Java for the following: Assume Employee table with
attributes (ENo, EName, Salary) is already created. 1. Insert 2. Update 3. Display 4. Exit.
*/
import java.sql.*;
import java.util.Scanner;
do {
// Display menu options
System.out.println("Menu:");
System.out.println("1. Insert");
System.out.println("2. Update");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
scanner.close();
}
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Set parameters
stmt.setInt(1, eno);
stmt.setString(2, ename);
stmt.setDouble(3, salary);
if (rowsAffected > 0) {
System.out.println("Employee record inserted successfully!");
} else {
System.out.println("Failed to insert employee record.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Set parameters
stmt.setDouble(1, newSalary);
stmt.setInt(2, eno);
if (rowsAffected > 0) {
System.out.println("Employee salary updated successfully!");
} else {
System.out.println("No employee found with the given ENo.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
while (rs.next()) {
int eno = rs.getInt("ENo");
String ename = rs.getString("EName");
double salary = rs.getDouble("Salary");
System.out.println(eno + "\t" + ename + "\t\t" + salary);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
===========================================================================================