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
Statement
to Execute Queries:- Creates a
Statement
object, which is used to execute SQL queries.
- Creates a
CRUD Operations
1. Create (Insert)
- This query inserts a new record into the
users
table with the specifiedname
andemail
. 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
ResultSet
is iterated to fetch data for each record in the table.
3. Update (Modify)
- The
UPDATE
query modifies thename
field for the user withid = 1
. - The
executeUpdate()
method returns the number of rows affected by the update.
4. Delete (Remove)
- The
DELETE
query removes the user withid = 1
from 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
SQLException
properly. 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
PreparedStatement
instead ofStatement
to avoid SQL injection vulnerabilities.
Comments
Post a Comment