Java
Learn how to connect to PostgreSQL databases in Sealos DevBox using Java
This guide will walk you through the process of connecting to a PostgreSQL database using Java within your Sealos DevBox project, including basic CRUD (Create, Read, Update, Delete) operations.
Prerequisites
- A Sealos DevBox project with Java environment
- A PostgreSQL database created using the Database app in Sealos
Setup
Download PostgreSQL JDBC Driver
To connect to the PostgreSQL server from a Java program, you need a PostgreSQL JDBC driver.
You can download the latest version of the driver on the jdbc.postgresql.org download page. The downloaded file is a jar file e.g., postgresql-42.7.1.jar.
Create a database configuration file
Create a file named db.properties
in your project directory with the following content:
Replace the placeholders with your actual PostgreSQL credentials from the Database app in Sealos.
Create a DatabaseConfig class
Create a new file named DatabaseConfig.java
with the following content:
The DatabaseConfig
class is responsible for loading database configuration from the db.properties
file. It has three static methods that expose the database configuration:
getDbUrl()
– Returns the database URL.getDbUsername()
– Returns the username.getDbPassword()
– Returns the password.
This class ensures that sensitive database credentials are not hardcoded in the application.
Create an Employee class
Create a new file named Employee.java
with the following content:
The Employee
class represents the data model for an employee. It includes fields for id, name, and position, along with a constructor, getters, setters, and a toString
method for easy printing of employee information.
Create a DB class
Create a new file named DB.java
with the following content:
The DB
class is responsible for database operations:
- The
getConnection()
method connects to the PostgreSQL database using the connection parameters fromDatabaseConfig
. - It returns a
Connection
object if successful, or throws aSQLException
if there's an error. - Other methods (
createTable
,insertEmployee
, etc.) use this connection to perform CRUD operations. - Each method opens a new connection, performs its operation, and then closes the connection using try-with-resources, ensuring proper resource management.
Create the main Java program
Create a new file named Main.java
with the following content:
The Main
class demonstrates the usage of the DB
class to perform various database operations:
- It creates a table, inserts sample data, retrieves and displays employees, updates an employee, deletes an employee, and displays the updated list.
- Each operation is wrapped in a try-catch block to handle potential
SQLException
s. - The program uses the methods from the
DB
class, which manage their own connections, ensuring that connections are properly opened and closed for each operation.
Compile and Run
To compile and run the example, use the following commands in your terminal:
If everything is set up correctly, you should see output demonstrating the CRUD operations on the employees table.
Best Practices
- Use a properties file to store database connection details.
- Implement a configuration class to load and provide access to database properties.
- Create a separate class for database connection management and operations.
- Use try-with-resources to ensure proper closure of database connections.
- Use prepared statements to prevent SQL injection.
- Handle exceptions appropriately and provide meaningful error messages.
Troubleshooting
If you encounter connection issues:
- Verify your database credentials in the
db.properties
file. - Ensure your PostgreSQL database is running and accessible from your DevBox environment.
- Check for any network restrictions in your DevBox environment.
- Confirm that the PostgreSQL JDBC driver JAR file is in the same directory as your Java files.
For more detailed information on using PostgreSQL with Java, refer to the official PostgreSQL JDBC driver documentation.