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: ThePreparedStatement
uses?
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 runSELECT
queries. It returns aResultSet
object.- The
ResultSet
is iterated to extract the data.
3. Update (Modify)
setString()
: Sets the updatedname
andemail
values.setInt()
: Sets theid
value to specify which record to update.executeUpdate()
: Executes the update query and returns the number of rows affected.
4. Delete (Remove)
setInt()
: Sets theid
value 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-resources
statement is used to automatically close thePreparedStatement
andConnection
objects 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 aSELECT
query and returns aResultSet
object 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