Objective: This segment introduces CRUD (create, read, update, and delete) operations in MySQL table using Java.
Prerequisites: MySQL setup is installed and running in the background. Also, the project has been developed and executed in Eclipse IDE (Integrated Development Environment).
To run the following program, you need to download the Download JDBC driver jar file. Once downloaded, you can import the library by right-clicking on your project in Eclipse -> Properties -> Java Build Path -> Libraries -> Add External JARs...
Java MySQL to perform JDBC CRUD operations
File: Employee.java
importjava.io.IOException;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.InputMismatchException;importjava.util.Random;importjava.util.Scanner;publicclassEmployee{staticStringempid;staticintch;staticStringfname="";staticStringlname="";staticStringmob="";staticStringdesignation="";staticdoublesalary=0;staticStringcity="";staticScannersc=newScanner(System.in);staticDataStoreHelperdsh=newDataStoreHelper();publicEmployee(Stringempid,Stringfname,Stringlname,Stringmob,Stringdesignation,doublesalary,Stringcity){Employee.empid=empid;Employee.fname=fname;Employee.lname=lname;Employee.mob=mob;Employee.designation=designation;Employee.salary=salary;Employee.city=city;}publicstaticStringempid(){Stringalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ";Stringdigits="0123456789";Randomr=newRandom();Stringgenrate="";while(genrate.length()!=7){intrPick=r.nextInt(4);if(rPick==1){genrate+=alphabets.charAt(r.nextInt(25));}elseif(rPick==3){genrate+=digits.charAt(r.nextInt(9));}}empid="KW_"+genrate;System.out.println("\nGenerated Employee ID "+empid);returnempid;}staticStringmobile(){System.out.print("\nEnter Mobile Number ");mob=sc.next();if(mob.matches("\\d{10}")){System.out.println("Mobile Number is Accepted");}else{System.out.println("Mobile Number is Not Valid (Must be 10 Digit)");mobile();}returnmob;}staticStringselect_desig(){do{try{System.out.println("________________________________");System.out.println("Select Your Designation");System.out.println("________________________________");System.out.println("1. Software Engineer\n2. Consultant\n3. Manager\n4. Other");System.out.println("________________________________");System.out.print("Enter Your Choice ");ch=sc.nextInt();}catch(InputMismatchExceptionime){System.out.println("\nWrong Choice Entered... Please Try Again");select_desig();}switch(ch){case1:designation="Software Engineer";salary=20000;break;case2:designation="Consultant";salary=25000;break;case3:designation="Manager";salary=30000;break;case4:designation="Other";salary=15000;break;default:System.out.println("\nWrong Choice Entered... Please Try Again");}}while(ch!=1&ch!=2&ch!=3&ch!=4);returndesignation;}staticStringcity(){Stringregex="^[a-zA-Z]+$";System.out.print("\nEnter Your City ");city=sc.next();if(city.matches(regex)&&city.length()>=3){System.out.println("City Name is Accepted");}else{System.out.println("Invalid City \n(Contains only alphabets and length should be greater than 2)");city();}returncity;}staticStringfirstname(){Stringregex="^[a-zA-Z]+$";System.out.print("\nEnter First Name ");fname=sc.next();if(fname.matches(regex)&&fname.length()>=2){System.out.println("FirstName is Accepted");}else{System.out.println("Invalid FirstName \n(Contains only alphabets and length should be greater than 2)");firstname();}returnfname;}staticStringlastname(){Stringregex="^[a-zA-Z]+$";System.out.print("\nEnter Last Name ");lname=sc.next();if(lname.matches(regex)&&lname.length()>=2){System.out.println("LastName is Accepted");}else{System.out.println("Invalid LastName \n(Contains only alphabets and length should be greater than 2)");firstname();}returnlname;}publicstaticvoidmainMenu()throwsClassNotFoundException,SQLException,IOException{do{try{System.out.println("________________________________");System.out.println("Welcome to Kodingwindow Portal");System.out.println("________________________________");System.out.println("1. Admin Login\n2. Sign In\n3. Sign Up\n4. Exit");System.out.println("________________________________");System.out.print("Enter Your Choice ");ch=sc.nextInt();}catch(InputMismatchExceptionime){System.out.println("\nWrong Choice Entered... Please Try Again");mainMenu();}switch(ch){case1:System.out.print("\nEnter User Name ");Stringuname=sc.next();System.out.print("\nEnter Password ");Stringpassword=sc.next();if(uname.equalsIgnoreCase("admin")&&password.equalsIgnoreCase("admin")){do{System.out.println("________________________________");System.out.println("1. Display All Employees\n2. Update Info\n3. Delete All Account\n4. Go to MainMenu");System.out.println("________________________________");System.out.print("Enter Your Choice ");try{ch=sc.nextInt();}catch(InputMismatchExceptionime){System.out.println("\nWrong Choice Entered... Please Try Again");}switch(ch){case1:try{dsh.viewAllEmployee(empid);}catch(Exceptione){System.out.println(e);}break;case2:break;case3:try{dsh.dropAllEmployee();}catch(Exceptione){System.out.println(e);}break;case4:mainMenu();default:System.out.println("\nWrong Choice Entered... Please Try Again");}}while(ch!=4);}else{System.out.println("\nWrong Username and Password");mainMenu();}break;case2:System.out.print("\nEnter Employee ID ");Stringemp=sc.next();if(emp.equals(empid)){do{System.out.println("________________________________");System.out.println("1. Display Info\n2. Update Info\n3. Remove Account\n4. Go to MainMenu");System.out.println("________________________________");System.out.print("Enter Your Choice ");try{ch=sc.nextInt();}catch(InputMismatchExceptionime){System.out.println("\nWrong Choice Entered... Please Try Again");}switch(ch){case1:try{dsh.viewEmployee(empid);}catch(Exceptione){System.out.println(e);}break;case2:dsh.updateEmployee(empid);break;case3:dsh.removeEmployee(empid);break;case4:mainMenu();default:System.out.println("\nWrong Choice Entered... Please Try Again");}}while(ch!=4);}else{mainMenu();}System.out.println(empid);break;case3:empid();firstname();lastname();mobile();select_desig();city();Employeee=newEmployee(empid,fname,lname,mob,designation,salary,city);try{dsh.addEmployee(e);}catch(Exceptionex){System.out.println(ex);}break;case4:System.exit(0);default:System.out.println("\nWrong Choice Entered... Please Try Again");}}while(ch!=4);}publicstaticvoidmain(String[]args)throwsClassNotFoundException,IOException,SQLException{try{Class.forName("com.mysql.cj.jdbk.Driver");}catch(ClassNotFoundExceptione){System.out.println("Please load MySQL JDBC driver");e.printStackTrace();return;}Connectioncon;try{con=DriverManager.getConnection("jdbc:mysql://localhost:3306/data","root","kodingwindow");System.out.println("Connection Established");}catch(SQLExceptione){System.out.println("Connection Failed");e.printStackTrace();return;}Statementst=con.createStatement();//st.executeUpdate("DROP TABLE EMPLOYEES");st.executeUpdate("CREATE TABLE EMPLOYEES(EMPID VARCHAR(11) PRIMARY KEY,FNAME VARCHAR(20),LNAME VARCHAR(20),MOB INT(10),DESIGNATION VARCHAR(20), SALARY INT(20), CITY VARCHAR(15))");System.out.println("Employees Table Created Successfully");mainMenu();}}
File: DataStoreHelper.java
importjava.io.IOException;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.InputMismatchException;importjava.util.Scanner;publicclassDataStoreHelper{publicvoidaddEmployee(Employeee1)throwsClassNotFoundException,SQLException,IOException{Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/data","root","kodingwindow");Statementst=con.createStatement();st.executeUpdate("INSERT INTO EMPLOYEES VALUES('"+Employee.empid+"','"+Employee.fname+"','"+Employee.lname+"','"+Employee.mob+"','"+Employee.designation+"','"+Employee.salary+"','"+Employee.city+"')");System.out.println("\nValues Inserted Successfully");}publicvoidviewEmployee(Stringempid)throwsClassNotFoundException,IOException{System.out.println("________________________________");try{Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/data","root","kodingwindow");Statementst=con.createStatement();ResultSetrs=st.executeQuery("SELECT * FROM EMPLOYEES WHERE EMPID='"+empid+"'");rs.next();System.out.println(rs.getString(2)+"'s Information");System.out.println("________________________________");System.out.println("EMPID: "+rs.getString(1)+"\nFirst Name: "+rs.getString(2)+"\nLast Name: "+rs.getString(3)+"\nMobile No.: "+rs.getString(4)+"\nDesignation: "+rs.getString(5)+"\nCurrent Salary: "+rs.getDouble(6)+"\nCity: "+rs.getString(7));}catch(SQLExceptione){System.out.println("Record Not Found");}System.out.println("________________________________\n");}publicvoidviewAllEmployee(Stringempid)throwsClassNotFoundException,IOException{intcount=0;try{Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/data","root","kodingwindow");Statementst=con.createStatement();ResultSetrs=st.executeQuery("SELECT * FROM EMPLOYEES");System.out.println("________________________________");while(rs.next()){System.out.println("EMPID: "+rs.getString(1)+"\nFirst Name: "+rs.getString(2)+"\nLast Name: "+rs.getString(3)+"\nMobile No.: "+rs.getString(4)+"\nDesignation: "+rs.getString(5)+"\nCurrent Salary: "+rs.getDouble(6)+"\nCity: "+rs.getString(7));System.out.println("________________________________");count++;}System.out.println("Total Number of Records "+count);}catch(SQLExceptione){System.out.println("Database is Empty");}}publicvoidremoveEmployee(Stringempid)throwsClassNotFoundException,SQLException,IOException{Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/data","root","kodingwindow");Statementst=con.createStatement();st.executeUpdate("DELETE FROM EMPLOYEES WHERE EMPID='"+empid+"'");System.out.println("Employee Removed Successfully");}publicvoidupdateEmployee(Stringempid)throwsClassNotFoundException,SQLException,IOException{Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/data","root","kodingwindow");Statementst=con.createStatement();Scannersc=newScanner(System.in);intch;try{System.out.println("________________________________");System.out.println("Update Your Information");System.out.println("________________________________");System.out.println("1. Mobile Number\n2. Designation\n3. City");System.out.println("________________________________");System.out.print("Enter Your Choice ");ch=sc.nextInt();switch(ch){case1:Stringmob=Employee.mobile();st.executeUpdate("UPDATE EMPLOYEES SET MOB='"+mob+"' WHERE EMPID='"+empid+"'");break;case2:Stringdesignation=Employee.select_desig();st.executeUpdate("UPDATE EMPLOYEES SET DESIGNATION='"+designation+"' WHERE EMPID='"+empid+"'");break;case3:Stringcity=Employee.city();st.executeUpdate("UPDATE EMPLOYEES SET CITY='"+city+"' WHERE EMPID='"+empid+"'");break;default:System.out.println("\nWrong Choice Entered... Please Try Again");}}catch(InputMismatchExceptionime){System.out.println("\nWrong Choice Entered... Please Try Again");Employee.select_desig();}System.out.println("Record Updated Successfully");}publicvoidupdateEmployeeDesig(Stringempid,Stringdesignation)throwsClassNotFoundException,SQLException,IOException{Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/data","root","kodingwindow");con.createStatement();System.out.println("Record Updated Successfully");}publicvoiddropAllEmployee()throwsSQLException{Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/data","root","kodingwindow");Statementst=con.createStatement();st.executeUpdate("DROP TABLE EMPLOYEES");System.out.println("All Employees Removed Successfully");}}
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.