← Back to Advanced Java Course | Chapter 8: Database & JPA | Lesson 2 of 4

Java JDBC CRUD Operations

CRUD stands for create, read, update and delete, the four basic things you do with stored data, like adding, looking at, changing, and throwing away cards in a file box. JDBC lets Java do all four in a database.
Syntax
java
PreparedStatement statement = connection.prepareStatement("INSERT INTO table_name (col1, col2) VALUES (?, ?)");
statement.setString(1, value1);
statement.setInt(2, value2);
statement.executeUpdate();

Create Operation (INSERT)

To add new records safely, avoid building SQL through raw string concatenation, which opens the door to SQL injection. PreparedStatements compile the query structure once and bind raw input values as parameters, keeping user-supplied data from ever being interpreted as SQL.

Example: Create Operation (INSERT)

java
import java.util.*;
public class Main {
	public static void main(String[] args) {
		List<String> table = new ArrayList<>();
		String sql = "INSERT INTO users (name) VALUES (?)"; // bound parameter, not concatenated
		String name = "Riya";
		table.add(name); // simulated insert
		System.out.println("Executed: " + sql + " with [" + name + "]");
	}
}

Update Operation (UPDATE)

UPDATE statements modify existing rows, with the columns to change and the WHERE clause both passed as bound PreparedStatement parameters rather than concatenated strings. Always check the executeUpdate() return value afterward, since it tells you how many rows actually matched and were changed.

Example: Update Operation (UPDATE)

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new ArrayList object and store it in table
		List<String> table = new ArrayList<>(List.of("Riya"));
		String sql = "UPDATE users SET name = ? WHERE name = ?";
		// Declare rowsChanged and set it to table.contains("Riya") ? 1 : 0
		int rowsChanged = table.contains("Riya") ? 1 : 0;
		table.set(0, "Riya Sharma");
		// Print a line to the console
		System.out.println("Executed: " + sql + " -- rows changed: " + rowsChanged);
	}
}

Batch SQL Operations

Batch processing speeds up bulk data tasks by bundling many individual INSERT, UPDATE, or DELETE statements together and sending them to the database in a single network round trip via executeBatch(), instead of paying that round-trip cost once per row.

Example: Batch SQL Operations

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		List<String> batch = List.of(
			"INSERT INTO logs VALUES ('a')",
			"INSERT INTO logs VALUES ('b')",
			"INSERT INTO logs VALUES ('c')"
		);
		// Print a line to the console
		System.out.println("Sending " + batch.size() + " statements in a single round trip via executeBatch()");
	}
}

Read Operation (SELECT)

Reading data back out of the database is done with a SELECT query executed through a PreparedStatement. The results come back as a ResultSet, which you iterate row by row using next(), pulling out each column with its corresponding typed getter method.

Example: Read Operation (SELECT)

java
import java.util.*;
public class Main {
	public static void main(String[] args) {
		List<String> table = List.of("Riya", "Aman");
		String sql = "SELECT name FROM users";
		for (String row : table) { // simulates iterating a ResultSet with next()
			System.out.println(row);
		}
	}
}

Delete Operation (DELETE)

Deleting rows uses a DELETE statement, again through a PreparedStatement so the row identifier is passed as a bound parameter rather than concatenated into the SQL string. executeUpdate() returns the number of rows actually removed, which is worth checking to confirm the delete matched what you expected.

Example: Delete Operation (DELETE)

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new ArrayList object and store it in table
		List<String> table = new ArrayList<>(List.of("Riya", "Aman"));
		String sql = "DELETE FROM users WHERE name = ?";
		// Declare target and set it to "Aman"
		String target = "Aman";
		// Declare removed and set it to table.remove(target)
		boolean removed = table.remove(target);
		// Print a line to the console
		System.out.println("Executed: " + sql + " -- rows removed: " + (removed ? 1 : 0));
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Building SQL with string concatenation, like "... WHERE name = '" + name + "'", which allows SQL injection; use ? placeholders.
  2. Writing UPDATE or DELETE without a WHERE clause, which changes or removes every row in the table.
  3. Adding statements with addBatch() but forgetting to call executeBatch(), so nothing is sent to the database.
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.