Memra

executeUpdate, INSERT/UPDATE/DELETE & SQL injection

Modifying data and why PreparedStatement is the only safe choice for user input.

executeUpdate

For SQL statements that modify data — INSERT, UPDATE, DELETE, DDL — use executeUpdate(). It returns an int representing the number of rows affected:

PreparedStatement ps = conn.prepareStatement(
    "UPDATE employees SET salary = ? WHERE id = ?");
ps.setDouble(1, 75000.00);
ps.setInt(2, 42);
int rowsAffected = ps.executeUpdate();
System.out.println("Updated " + rowsAffected + " row(s)");

SQL injection — the danger of string concatenation

Never build SQL by concatenating user-supplied strings:

// DANGEROUS — do NOT do this:
String sql = "SELECT * FROM users WHERE name = '" + userInput + "'";

If userInput is ' OR '1'='1, the query becomes WHERE name = '' OR '1'='1' — which returns every row. An attacker can also drop tables or exfiltrate data.

Safe version with PreparedStatement:

PreparedStatement ps = conn.prepareStatement(
    "SELECT * FROM users WHERE name = ?");
ps.setString(1, userInput);  // driver escapes the value safely
ResultSet rs = ps.executeQuery();

The ? placeholder is never interpreted as SQL — the driver sends the literal value to the database as a bind parameter, separate from the query structure. Even a malicious string is treated as plain data.

NORMAL ~/memra/learn/java-from-zero/updates-and-sql-injection utf-8 LF