JDBC
JDBC
• Demo
https://www.geeksforgeeks.org/establishing-jdbc-connection-in-java/
Querying and Updating
the Database
Introduction to SQL Queries in JDBC
• JDBC allows executing SQL queries to interact with the database
• Queries include SELECT, INSERT, UPDATE, DELETE
• Queries are executed using the Statement or PreparedStatement
interface
• Data retrieved is stored in a ResultSet object
• Always handle SQL exceptions with proper error handling
The Statement Interface
• Used to execute basic SQL queries
• Methods:
• executeQuery(sql) – for SELECT queries
• executeUpdate(sql) – for INSERT, UPDATE, DELETE queries
• execute(sql) – for complex queries with multiple results
• Suitable for simple SQL commands without parameters
PreparedStatement for
Parameterized Queries
• PreparedStatement is used for parameterized queries
• Precompiles the SQL query for better performance
• Avoids SQL injection attacks by using placeholders (?)
• Handle specific SQL errors like invalid syntax and connection failures
Closing Resources
• Always close Connection, Statement, and ResultSet objects
• Use try-with-resources in Java 7+ for automatic resource
management