Java JDBC program to perform CRUD Operation on table using Updatable resultset
Simple Java JDBC program to perform all CRUD operation on data stored in student table using updable resultset.
Code:
package aj.pkg12;import java.sql.*;
import java.util.*;
public class AJ12 {
public static void main(String args[])throws Exception{
int i=0 , op=0;
Float r;
String s = null,str = null;
String ch = null;
Class.forName("com.mysql.jdbc.Driver");
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");
Scanner sc= new Scanner(System.in);
Statement stm = cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = null;
do{
System.out.println("Which operation do you want to perform ?\n1.Create Records\n2.Read Records\n3.Update Records\n4.Delete Records");
op = sc.nextInt();
switch(op){
case 1:
rs = stm.executeQuery("Select * from student_table");
System.out.println("Enter RollNumber : ");
i = sc.nextInt();
sc.nextLine();
System.out.println("Enter Name : ");
str = sc.nextLine();
System.out.println("Enter Result : ");
r = Float.parseFloat(sc.nextLine());
rs.moveToInsertRow();
rs.updateInt("roll_number", i);
rs.updateString("name",str);
rs.updateFloat("result_p", r);
rs.insertRow();
rs.moveToCurrentRow();
break;
case 2:
rs = stm.executeQuery("SELECT * FROM student_table");
int n = 1;
while(rs.next()){
System.out.println("Record " + n);
System.out.println("Roll_Number : "+rs.getInt(1));
System.out.println("Name : "+ rs.getString(2));
System.out.println("Result : "+rs.getInt(3));
n++;}
break;
case 3:
System.out.println("Enter roll_number of record where you want to update");
int j = sc.nextInt();
rs = stm.executeQuery("Select * from student_table where roll_number = "+j);
System.out.println("Enter details for updation: ");
System.out.println("Enter RollNumber : ");
i = sc.nextInt();
sc.nextLine();
System.out.println("Enter Name : ");
s = sc.nextLine();
System.out.println("Enter Result : ");
r = Float.parseFloat(sc.nextLine());
rs.absolute(1);
rs.updateInt("roll_number", i);
rs.updateString("name", s);
rs.updateFloat("result_p", r);
rs.updateRow();
break;
case 4:
System.out.println("Enter roll_number of record for deletion.");
j = sc.nextInt();
rs = stm.executeQuery("Select * from student_table where roll_number = "+j);
rs.first();
rs.deleteRow();
System.out.println("Records deleted successfully");
break;
default:
System.out.println("Enter correct choice");
}
System.out.println("Do you want to perform more operations ? (Y/N)");
ch = sc.next();
}while(ch.equals("Y") || ch.equals("y"));
stm.close();
cn.close();
}
}
Comments
Post a Comment