Nearby lessons

34 of 37

JDBC - CRUD 5: Full Menu-Driven Example

📌 What You Will Learn
  • The difference between Select and Non-Select operations
  • executeQuery vs executeUpdate — when to use which
  • Reading results with the ResultSet methods
  • Complete CRUD programs: Insert, Select, Update, Delete
  • The ResultSet object and how it works

CRUD 5: Full Menu-Driven Example is a fundamental part of database programming with JDBC. This lesson explains CRUD Program 5 — Full Menu-Driven Example with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

CRUD Program 5 — Full Menu-Driven Example

A classic exam program: a menu that lets the user choose Insert / Select / Update / Delete. This uses Scanner for input and switch for the menu:

Trainer's Note: Security warning: the menu above is for learning. In real code, never build SQL by joining user input with + — that invites SQL injection (Chapter 7). Always use PreparedStatement with ? placeholders.
In simple words: Never build SQL by joining user input with `+` — that invites SQL injection. Use a PreparedStatement with ? placeholders so the database treats the user's input as data, not as part of the query.
Example01
JCode Cell
1import java.sql.*;
2import java.util.Scanner;
3 
4public class MenuDemo {
5 public static void main(String[] args) throws Exception {
6 Connection con = DriverManager.getConnection(
7 "jdbc:mysql://localhost:3306/company", "root", "password");
8 Statement st = con.createStatement();
9 Scanner sc = new Scanner(System.in);
10 
11 System.out.println("1. Insert 2. Select 3. Update 4. Delete");
12 System.out.print("Enter your option: ");
13 int opt = sc.nextInt();
14 
15 switch (opt) {
16 case 1:
17 st.executeUpdate("INSERT INTO employee VALUES (103, 'Anil', 45000)");
18 System.out.println("Inserted");
19 break;
20 case 2:
21 ResultSet rs = st.executeQuery("SELECT * FROM employee");
22 while (rs.next())
23 System.out.println(rs.getInt(1) + " " + rs.getString(2));
24 break;
25 case 3:
26 st.executeUpdate("UPDATE employee SET salary = 48000 WHERE id = 103");
27 System.out.println("Updated");
28 break;
29 case 4:
30 st.executeUpdate("DELETE FROM employee WHERE id = 103");
31 System.out.println("Deleted");
32 break;
33 default:
34 System.out.println("Invalid option");
35 }
36 con.close();
37 }
38}
📝 Key Takeaways
  • Select ops (SELECT) use executeQuery() → ResultSet.
  • Non-select ops (INSERT/UPDATE/DELETE) use executeUpdate() → row count.
  • rs.next() moves the cursor; getInt/getString/getDouble read values.
  • CRUD = Create(INSERT), Retrieve(SELECT), Update, Delete.
  • Always close the connection after work.
  • Use PreparedStatement for real applications (SQL injection safety).

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1