Using PreparedStatement in JDBC for CRUD (Create, Read, Update, Delete) operations provides better security and performance compared to using a Statement, especially by protecting against SQL injection attacks. Below is an example of how to use PreparedStatement for CRUD operations in a PostgreSQL database.
Full Java Example of CRUD Operations Using
PreparedStatement
Explanation of Each CRUD Operation:
1. Create (Insert)
?placeholders: ThePreparedStatementuses?as placeholders for the values you want to insert.setString(): Sets the value of the placeholder to a string.executeUpdate(): Executes the insert query.
2. Read (Select)
executeQuery(): Used to runSELECTqueries. It returns aResultSetobject.- The
ResultSetis iterated to extract the data.
3. Update (Modify)
setString(): Sets the updatednameandemailvalues.setInt(): Sets theidvalue to specify which record to update.executeUpdate(): Executes the update query and returns the number of rows affected.
4. Delete (Remove)
setInt(): Sets theidvalue to specify which record to delete.executeUpdate(): Executes the delete query and returns the number of rows deleted.
Important Notes:
- PreparedStatement is more secure because it prevents SQL injection by ensuring that input data is automatically escaped before being executed.
- Auto-closeable Resources: The
try-with-resourcesstatement is used to automatically close thePreparedStatementandConnectionobjects when they are no longer needed. - Exception Handling: Always handle SQL exceptions to avoid crashes and to log meaningful error messages.
Summary of PreparedStatement Methods:
setString(int parameterIndex, String value): Sets a string value for the specified parameter index.setInt(int parameterIndex, int value): Sets an integer value for the specified parameter index.executeUpdate(): Executes the SQL query (forINSERT,UPDATE, orDELETE) and returns the number of affected rows.executeQuery(): Executes aSELECTquery and returns aResultSetobject containing the results.
This approach should be sufficient for performing secure and efficient CRUD operations in your database using JDBC and PreparedStatement.
Comments
Post a Comment