Skip to content

Commit 7bdbf84

Browse files
committed
docs(jdbc): add deep-dive explanation of JDBC Statement types
What - Added an in-depth guide explaining the three JDBC statement interfaces: 1. `Statement` 2. `PreparedStatement` 3. `CallableStatement` - Covered creation, execution, use cases, and differences between them. - Included practical code examples for each: - `Statement stmt = con.createStatement();` - `PreparedStatement pstmt = con.prepareStatement("SELECT ... WHERE deptno = ?");` - `CallableStatement cstmt = con.prepareCall("{call getStudentData(?,?)}");` - Explained key supporting concepts: - `Connection` and `ResultSet` lifecycles. - Methods `executeQuery()`, `executeUpdate()`, and `execute()`. - Security aspects like SQL injection prevention with PreparedStatement. - Stored procedure calls using CallableStatement. - Added real-world usage example for inserting data using PreparedStatement. Why - Developers often confuse when to use Statement vs. PreparedStatement vs. CallableStatement. - Provides clarity on efficiency, security, and suitability for different query types. - Establishes best practices like: - Prefer PreparedStatement for user inputs. - Use CallableStatement for stored procedures. - Limit Statement to simple, static SQL. How - Structured documentation into sections: - Overview → Creation → Execution → When to Use → Benefits → Practical Examples. - Highlighted downsides of `Statement` (prone to SQL injection, inefficient). - Showed how PreparedStatement improves performance via precompilation and parameter binding. - Described how CallableStatement bridges Java code and server-side business logic. - Reinforced resource management: always close `ResultSet`, `Statement`, and `Connection`. Key Takeaways - **Statement** → best for simple, one-off queries without parameters. - **PreparedStatement** → best for queries with parameters, safer and more efficient. - **CallableStatement** → best for stored procedures or DB-side functions. - Closing resources or using try-with-resources is mandatory to avoid leaks. Real-life Applications - Login/authentication systems → PreparedStatement to validate credentials safely. - Banking apps → CallableStatement to call complex stored procedures for transactions. - Reporting dashboards → PreparedStatement for dynamic filters in queries. - ETL or batch operations → Statement for static, bulk schema modifications. Notes - Use `PreparedStatement` as the default choice when dealing with user input. - Stored procedures differ across databases → ensure JDBC driver compatibility. - Resource handling should always use try-with-resources in modern Java. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent fa113b8 commit 7bdbf84

File tree

1 file changed

+18
-25
lines changed

1 file changed

+18
-25
lines changed
Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,19 @@ CallableStatement — including how they’re created, when to use them, and why
1010
- It is created via a Connection object’s createStatement() method.
1111
- Typically used for static SQL queries without parameters.
1212

13-
### How to Create a Statement
13+
### How to Create a Statement:
1414

1515
// Assume you already have a Connection object "con"
1616
Statement stmt = con.createStatement();
1717

1818
### Executing Queries with Statement
1919

2020
1. SELECT queries:
21-
2221
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
2322

2423
- Returns a ResultSet that you can iterate over to read rows from the database.
2524

2625
2. DML queries (INSERT, UPDATE, DELETE):
27-
2826
int rowsAffected = stmt.executeUpdate(INSERT INTO students VALUES (101, 'Alice', 'NY', 10));
2927

3028
- Returns an integer indicating how many rows were affected.
@@ -54,7 +52,6 @@ PreparedStatement pstmt = con.prepareStatement(sql);
5452
### Executing Queries with PreparedStatement
5553

5654
1. Setting Parameters:
57-
5855
pstmt.setInt(1, 10); // Replaces the first "?" with 10
5956

6057
2. Executing:
@@ -64,7 +61,7 @@ PreparedStatement pstmt = con.prepareStatement(sql);
6461
- INSERT/UPDATE/DELETE:
6562
int rowsAffected = pstmt.executeUpdate();
6663

67-
### When to Use
64+
### When to Use:
6865
- For queries with parameters** (e.g., user input or variables in your code).
6966
- If you need to execute the same SQL statement multiple times with different parameter values,
7067
PreparedStatement is more efficient than Statement because the query can be precompiled by the database.
@@ -74,8 +71,8 @@ PreparedStatement pstmt = con.prepareStatement(sql);
7471

7572
### Key Benefits
7673
1. Efficiency: The SQL statement is parsed/compiled once, and can be executed multiple times.
77-
2. **Security: Automatic handling of special characters in parameters reduces the risk of injection attacks.
78-
3. **Readability: Clear separation of the SQL query structure from the data being inserted.
74+
2. Security: Automatic handling of special characters in parameters reduces the risk of injection attacks.
75+
3. Readability: Clear separation of the SQL query structure from the data being inserted.
7976

8077
---
8178

@@ -91,15 +88,13 @@ PreparedStatement pstmt = con.prepareStatement(sql);
9188
// Example stored procedure call: {call getStudentData(?,?)}
9289
CallableStatement cstmt = con.prepareCall("{call getStudentData(?,?)}");
9390

94-
### Using Parameters
95-
91+
### Using Parameters:
9692
- You can set IN parameters with setXxx() methods, and register OUT parameters if the procedure returns values.
9793

9894
cstmt.setInt(1, 101); // Setting an IN parameter
9995
cstmt.registerOutParameter(2, Types.VARCHAR); // Registering an OUT parameter
10096

101-
### Executing
102-
97+
### Executing:
10398
- Execute the stored procedure:
10499

105100
cstmt.execute();
@@ -108,24 +103,23 @@ CallableStatement cstmt = con.prepareCall("{call getStudentData(?,?)}");
108103

109104
String studentName = cstmt.getString(2);
110105

111-
### When to Use
112-
106+
### When to Use:
113107
- When you have stored procedures or functions in your database that perform complex tasks.
114108
- Useful for reusing database-side logic and possibly improving performance.
115109

116110
---
117111

118-
## Important Terms and Applications
112+
## Important Terms and Applications:
119113

120-
1. Connection
114+
1. Connection:
121115
- Represents a session with a specific database.
122116
- All statements (Statement, PreparedStatement, CallableStatement) require an active Connection.
123117

124-
2. ResultSet
125-
- Represents the **result** of a SELECT query.
118+
2. ResultSet:
119+
- Represents the result of a SELECT query.
126120
- Provides methods like next(), getInt(), getString(), etc. to **iterate through rows.
127121

128-
3. executeQuery() vs. executeUpdate() vs. execute()
122+
3. executeQuery() vs. executeUpdate() vs. execute():
129123
- executeQuery(): For SELECT statements (returns a ResultSet).
130124
- executeUpdate(): For INSERT, UPDATE, DELETE statements (returns an integer indicating rows affected).
131125
- execute(): General-purpose method for statements that might return multiple results or unknown types
@@ -139,15 +133,15 @@ CallableStatement cstmt = con.prepareCall("{call getStudentData(?,?)}");
139133
- Pre-compiled routines on the database server that can be invoked using CallableStatement.
140134
- Often used to encapsulate business logic and improve performance by reducing network calls.
141135

142-
6. Resource Management
143-
- Always close your ResultSet, Statement, and Connection objects in a finally block (or use try-with-resources)
136+
6. Resource Management:
137+
- Always close your ResultSet, Statement, and Connection objects in a final block (or use try-with-resources)
144138
to avoid memory leaks.
145139

146140
---
147141

148-
## Practical Example:
142+
Practical Example:
149143

150-
### Using PreparedStatement for a Parameterized Query
144+
Using PreparedStatement for a Parameterized Query:
151145

152146
// 1. Get a connection
153147
Connection con = DriverManager.getConnection("jdbc:sqlite:univ.db");
@@ -171,11 +165,10 @@ System.out.println("Rows inserted: " + rowsInserted);
171165
// 6. Close resources
172166
pstmt.close();
173167
con.close();
174-
```
175168

176169
---
177170

178-
## Summary of Statement Types
171+
## Summary of Statement Types:
179172

180173
1. Statement:
181174
- Simple, ad-hoc queries without parameters.
@@ -191,4 +184,4 @@ con.close();
191184
- Invokes stored procedures or functions in the database.
192185
- Useful for encapsulating complex logic on the database server side.
193186

194-
Using these three interfaces effectively allows you to write **clean, efficient, and secure database-access code in Java.
187+
Using these three interfaces effectively allows you to write clean, efficient, and secure database-access code in Java.

0 commit comments

Comments
 (0)