Executing SQL Queries with JDBC
⏱ Estimated reading time: 2 min
JDBC (Java Database Connectivity) provides a standard API to execute SQL queries and retrieve results from relational databases. SQL operations are broadly classified into Data Definition Language (DDL) and Data Manipulation Language (DML) operations.
1. Steps to Execute SQL Queries
-
Load JDBC Driver
-
Establish Database Connection
-
Create Statement Object
-
Execute SQL Query
-
Use
executeQuery()for SELECT statements -
Use
executeUpdate()for INSERT, UPDATE, DELETE, CREATE, DROP
-
Process ResultSet (for SELECT)
-
Close Resources
2. Example 1: SELECT Query
3. Example 2: INSERT Query
4. Example 3: UPDATE and DELETE Queries
UPDATE
DELETE
5. Using PreparedStatement (Recommended)
-
Prevents SQL injection
-
Precompiles SQL queries for better performance
6. Key Points
-
executeQuery()→ For SELECT statements, returns ResultSet -
executeUpdate()→ For INSERT, UPDATE, DELETE, returns number of affected rows -
Always close JDBC resources to prevent memory leaks
-
Prefer PreparedStatement over Statement for dynamic queries and security
7. Conclusion
Executing SQL queries using JDBC allows Java applications to interact dynamically with relational databases, enabling CRUD operations, transaction management, and data retrieval. Proper use of Statement, PreparedStatement, and ResultSet ensures efficient, secure, and maintainable database programming.
Register Now
Share this Post
← Back to Tutorials