Nearby lessons

10 of 37

JDBC - Statement, executeQuery and executeUpdate

📌 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

Statement, executeQuery and executeUpdate is a fundamental part of database programming with JDBC. This lesson explains Select vs Non-Select Operations, ecuteQuery vs executeUpdate and Statement vs PreparedStatement vs CallableStatement with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Select vs Non-Select Operations

In JDBC, every SQL operation is one of two types:

TypeSQL examplesWhich method
Select operationSELECT (returns rows of data)executeQuery() → returns ResultSet
Non-Select operationINSERT, UPDATE, DELETE (change data)executeUpdate() → returns row count

Simple memory: if the query gives you data back → executeQuery. If it changes data (or the table structure) → executeUpdate.

executeQuery vs executeUpdate

PointexecuteQuery()executeUpdate()
Used forSELECTINSERT / UPDATE / DELETE, DDL
ReturnsA ResultSet (the rows)An int (how many rows changed)
For DDL (CREATE/DROP)NoYes (returns 0)
Can you read data?YesNo
In simple words: The method you pick depends on what the query returns: `executeQuery()` gives back a ResultSet, `executeUpdate()` gives back a row count. SELECT is a select operation; INSERT, UPDATE and DELETE are non-select operations.
Example02
JCode Cell
1// Non-select: INSERT / UPDATE / DELETE
2int rows = st.executeUpdate("INSERT INTO emp VALUES (101,'Rahul')");
3System.out.println("Rows changed: " + rows);
4 
5// Select: SELECT
6ResultSet rs = st.executeQuery("SELECT * FROM emp");

Statement vs PreparedStatement vs CallableStatement

PointStatementPreparedStatementCallableStatement
SQL with valuesJoined with + (unsafe)? placeholders (safe)? placeholders
CompiledEvery timeOnce (reusable)Once (procedure call)
SQL injection riskHighNoneNone
Used forDDL, one-time queriesRepeated value queries (INSERT/UPDATE)Stored procedures
PerformanceSlowest for repeatsFastFast

Statement vs PreparedStatement vs CallableStatement

PointStatementPreparedStatementCallableStatement
Used forSimple SQLSQL with values (repeated)Stored procedures
Create bycon.createStatement()con.prepareStatement(sql)con.prepareCall("{call ...}")
PlaceholdersNoYes (? with setXxx)Yes (? with setXxx + registerOut)
SQL injection safe?NoYesYes
Best performance whenOne-time queriesSame query, many valuesProcedure calls

Real-Time Coding Standards

The classic material teaches the habits professional developers follow. These are must-know for placements:

StandardWhy
Always close resources (ResultSet, Statement, Connection)Otherwise connections leak and the database runs out of connections
Use try-with-resources (Java 7+)Resources close automatically even if an error happens
Use PreparedStatement instead of Statement for valuesProtects against SQL injection (Chapter 7)
Handle exceptions with try-catch (or throws)A crash must never leave connections open
Put the driver JAR in classpath (or use a build tool)The driver must be findable at run time
Use a connection pool in real applicationsCreating a connection is expensive; reuse them
In simple words: A professional never lets a connection leak. Every Connection, Statement and ResultSet you forget to close eats up a database connection, until the database refuses new ones.

The Professional Way — try-with-resources

Trainer's Note: This is the recommended modern style: put Connection, Statement and ResultSet inside the try brackets. When the try ends — normally or with an error — all three close by themselves. No con.close() needed, no forgotten resources.
Example06
JCode Cell
1import java.sql.*;
2 
3public class ModernStyle {
4 public static void main(String[] args) {
5 // resources close automatically when the try ends
6 try (Connection con = DriverManager.getConnection(
7 "jdbc:mysql://localhost:3306/company", "root", "password");
8 Statement st = con.createStatement();
9 ResultSet rs = st.executeQuery("SELECT * FROM employee")) {
10 
11 while (rs.next()) {
12 System.out.println(rs.getInt(1) + " " + rs.getString(2));
13 }
14 } catch (SQLException e) {
15 System.out.println("Database error: " + e.getMessage());
16 }
17 // con, st and rs are closed automatically here - no manual close needed
18 }
19}
📝 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