Advance Java

Write JDBC program which executes the following operation by executing batch statement.
  • Create table
  • Insert new record to respective table
  • Update existing record of respective table
  • Delete all records from respective table


import java.sql.*;
import java.util.Scanner;
 
public class DatabaseCRUD {
 
    public static void main(String[] args) {
        String dbConn = "jdbc:mysql://localhost:3306/college";
        String username = "root";
        String pwd = "";
        String query1 = "CREATE TABLE IF NOT EXISTS studentInfo ("
                + "id INTEGER AUTO_INCREMENT PRIMARY KEY, "
                + "rollno VARCHAR(12) NOT NULL, "
                + "name VARCHAR(50) NOT NULL,"
                + "branch VARCHAR(20) NOT NULL"
                + ")",
               
                query2 = "INSERT INTO studentInfo"
                + "(rollno, name, branch)"
                + "values(101, 'Ram', 'ME')",
               
                query3 = "UPDATE studentInfo SET branch = 'CE' WHERE rollno = 101",
               
                query4 = "DELETE FROM studentInfo";
 
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(dbConn, username, pwd);
            conn.setAutoCommit(false);
            Statement st = conn.createStatement();
            st.addBatch(query1);
            st.addBatch(query2);
            st.addBatch(query3);
            st.addBatch(query4);
            int[] i = st.executeBatch();
            conn.commit();
           
            for(int j=0; j<i.length; j++) {
                System.out.println(i[j] + " rows affected.");
            }
           
            st.close();
            conn.close();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}




Post a Comment

0 Comments