Here’s an example of how to use JDBC Statement for performing CRUD (Create, Read, Update, Delete) operations on a PostgreSQL database.
Prerequisites
Ensure you have:
- A PostgreSQL database running.
- The PostgreSQL JDBC driver added to your project.
- A table in the database for performing CRUD operations.
Example SQL for creating a users table:
JDBC CRUD Operations
- Create – Insert a record into the table.
- Read – Retrieve records from the table.
- Update – Modify an existing record.
- Delete – Remove a record from the table.
Full Example of JDBC CRUD Operations Using Statement
Explanation:
Creating a Connection:
- Establishes a connection to the PostgreSQL database using the provided URL, username, and password.
Using
Statementto Execute Queries:- Creates a
Statementobject, which is used to execute SQL queries.
- Creates a
CRUD Operations
1. Create (Insert)
- This query inserts a new record into the
userstable with the specifiednameandemail. executeUpdate()is used for queries that modify the database (INSERT, UPDATE, DELETE).
2. Read (Select)
- The
executeQuery()method is used to run a SELECT query, returning aResultSet. - The
ResultSetis iterated to fetch data for each record in the table.
3. Update (Modify)
- The
UPDATEquery modifies thenamefield for the user withid = 1. - The
executeUpdate()method returns the number of rows affected by the update.
4. Delete (Remove)
- The
DELETEquery removes the user withid = 1from the table. - The
executeUpdate()method returns the number of rows deleted.
Closing Resources:
In the above example, try-with-resources is used to automatically close the Connection and Statement objects after the execution of the operations.
Additional Notes:
- Exceptions Handling: Make sure to handle
SQLExceptionproperly. In this example, it is printed usinge.printStackTrace(), but you might want to log it or handle it in other ways. - SQL Injection Prevention: For more complex SQL operations, consider using
PreparedStatementinstead ofStatementto avoid SQL injection vulnerabilities.
Comments
Post a Comment