Go
Learn how to connect to PostgreSQL databases in Sealos Devbox using Go
This guide will walk you through the process of connecting to a PostgreSQL database using Go within your Sealos Devbox project.
Prerequisites
- A Sealos Devbox project with Go environment
- A PostgreSQL database created using the Database app in Sealos
Install Required Packages
In your Cursor terminal, install the necessary packages:
These commands install:
github.com/lib/pq
: A pure Go PostgreSQL driver for the database/sql packagegithub.com/joho/godotenv
: A Go port of the Ruby dotenv library
Connection Setup
Set up the environment variables
First, let's set up the environment variables for our database connection. Create a .env
file in your project root with the following content:
Replace the placeholders with your actual PostgreSQL credentials from the Database app in Sealos.
Create the main.go file
Create a new file named main.go
with the following content:
Let's break down the main components of this code:
-
Imports: We import necessary packages, including
database/sql
for database operations andgithub.com/lib/pq
as the PostgreSQL driver. -
Employee struct: Defines the structure for our employee data.
-
connectDB function: Loads environment variables, constructs the connection string, and establishes a connection to the database.
-
createTable function: Creates the
employees
table if it doesn't exist. -
insertEmployee function: Inserts a new employee into the database.
-
getEmployees function: Retrieves all employees from the database.
-
main function: Orchestrates the program flow, demonstrating database connection, table creation, data insertion, and retrieval.
Usage
To run the application, use the following command in your Cursor terminal:
This will execute the main
function, demonstrating the connection to the database, table creation, data insertion, and querying.
Best Practices
- Use environment variables for database credentials.
- Always handle potential errors using proper error checking.
- Close the database connection after operations are complete.
- Use prepared statements for queries to prevent SQL injection.
- Consider using a connection pool for better performance in production environments.
Troubleshooting
If you encounter connection issues:
- Verify your database credentials in the
.env
file. - Ensure your PostgreSQL database is running and accessible.
- Check for any network restrictions in your Devbox environment.
- Confirm that the required packages are correctly installed.
For more detailed information on using PostgreSQL with Go, refer to the lib/pq documentation.