Write a Java program to accept the details of student (rollNo, name, percentage) from the user and insert it into the table (Use PreparedStatement class)
Write a Java program to accept the details of student (rollNo, name, percentage) from the user and insert it into the table (Use PreparedStatement class)
Program:
import java.sql.*;
import java.io.*;
class Student {
    public static void main(String args[]) throws SQLException, ClassNotFoundException, IOException {
        String name;
        int rollNo;
        float percentage;
        char ch;
        BufferedReader br;
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        COnnection con = DriverManager.getConnection("jdbc:odbc:studentDSN");
        do {
            PreparedStatement stmt = con.prepareStatement("insert into student values(?,?,?)");
            br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter Roll No:");
            rollNo = Integer.parseInt(br.readLine());
            System.out.println("Enter Name:");
            name = br.readLine();
            System.out.println("Enter Marks:");
            percentage = Float.valueOf(br.readLine());
            stmt.setInt(1, rollNo);
            stmt.setString(2, name);
            stmt.setFloat(3, percentage);
            int r = stmt.executeUpdate();
            if(r>0) {
                System.out.println("Record Inserted.");
            }
            stmt.close();
            System.out.println("Add more Record Y/N");
            ch = (char)(br.read());
        } while(ch == 'y' || ch == 'Y');
        Statement s = con.createStatement();
        ResultSet res = s.executeQuery("select * from student");
        while(res.next()){
            System.out.println("Roll No: "+res.getInt(1));
            System.out.println("Name: "+res.getString(2));
            System.out.println("Percentage: "+res.getFloat(3));
        }
        res.close();
        con.close();
    }
}
Comments
Post a Comment