Thursday, 3 April 2025

Write a JDBC program to insert a record in student table (rollno,name, course, percentage) and display all records of student table.



iimport java.sql.*;

import java.util.Scanner;

 

class InsertStudent1 {

    public static void main(String args[]) throws Exception {

        Connection con;

        PreparedStatement pstmt;

        Statement stmt;

        Scanner sc = new Scanner(System.in);

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

        

      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mca", "root", "");

          System.out.print("Enter Roll Number: ");

        int rollno = sc.nextInt();

        

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

        String name = sc.next();

        

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

        String course = sc.next();

        

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

        double percentage = sc.nextDouble();

        

               pstmt = con.prepareStatement("INSERT INTO student1 (rollno, name, course, percentage) VALUES (?, ?, ?, ?)");

        pstmt.setInt(1, rollno);

        pstmt.setString(2, name);

        pstmt.setString(3, course);

        pstmt.setDouble(4, percentage);

        

                int n = pstmt.executeUpdate();

        System.out.println(n + " record(s) inserted..");

        

                stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery("SELECT * FROM student1");

        

        System.out.println("\nStudent Records:");

        while (rs.next()) {

            System.out.println("Roll No: " + rs.getInt("rollno") + ", Name: " + rs.getString("name") + ", Course: " + rs.getString("course") + ", Percentage: " + rs.getDouble("percentage"));

        }

            rs.close();

        stmt.close();

        pstmt.close();

        con.close();

        sc.close();

    }

}