w3resource

PostgreSQL and Go (Golang): Setup, CRUD Examples, and Connection Guide


Connecting PostgreSQL with Go (Golang): Full Guide with Examples

Integrating PostgreSQL with Go (Golang) is a powerful combination, enabling you to manage data in a relational database through a highly efficient language. This guide covers setting up a PostgreSQL connection, creating tables, and performing CRUD operations in Go.

Step 1: Install pq PostgreSQL Driver for Go

To interact with PostgreSQL in Go, you need the pq driver, a popular and lightweight package for database connectivity. Install it using:

go get -u github.com/lib/pq

Step 2: Setting Up a Connection

Define your PostgreSQL connection using the database/sql package alongside the pq driver. Here’s an example of connecting Go with PostgreSQL:

package main

Code:

import (
	"database/sql"          // Provides SQL database functionality
	"fmt"                   // For printing messages
	"log"                   // For logging errors
	_ "github.com/lib/pq"   // Import pq for PostgreSQL driver
)

func main() {
	// Define the connection string with PostgreSQL credentials
	connStr := "user=your_username password=your_password dbname=your_database sslmode=disable"
	
	// Open a database connection
	db, err := sql.Open("postgres", connStr)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close() // Ensure connection closes after function ends

	// Ping to confirm connection
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connected to PostgreSQL successfully!")
}

Step 3: Creating a Table

With the connection established, let’s create a table using Go.

Code:

func createTable(db *sql.DB) {
	// Define the SQL query for creating a new table
	createTableSQL := `
	CREATE TABLE IF NOT EXISTS employees (
		id SERIAL PRIMARY KEY,
		name VARCHAR(100),
		position VARCHAR(100),
		hire_date DATE
	);`
	
	// Execute the SQL query
	_, err := db.Exec(createTableSQL)
	if err != nil {
		log.Fatalf("Failed to create table: %v", err)
	}
	fmt.Println("Table created successfully.")
}

Step 4: Performing CRUD Operations in Go

Insert Data

Here’s how to insert data into the employees table.

Code:

func insertEmployee(db *sql.DB, name, position, hireDate string) {
	insertSQL := `
	INSERT INTO employees (name, position, hire_date)
	VALUES ($1, $2, $3);`
	
	_, err := db.Exec(insertSQL, name, position, hireDate)
	if err != nil {
		log.Fatalf("Failed to insert employee: %v", err)
	}
	fmt.Println("Employee inserted successfully.")
}

// Usage:
// insertEmployee(db, "Kris Taaniel", "Developer", "2023-07-01")

Query Data

Retrieve data from the employees table:

Code:

func getEmployees(db *sql.DB) {
	rows, err := db.Query("SELECT * FROM employees;")
	if err != nil {
		log.Fatalf("Failed to fetch employees: %v", err)
	}
	defer rows.Close()

	for rows.Next() {
		var id int
		var name, position, hireDate string
		if err := rows.Scan(&id, &name, &position, &hireDate); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("ID: %d, Name: %s, Position: %s, Hire Date: %s\n", id, name, position, hireDate)
	}
}

Update Data

Update an employee’s position by their ID.

Code:

func updateEmployeePosition(db *sql.DB, id int, newPosition string) {
	updateSQL := `
	UPDATE employees
	SET position = $1
	WHERE id = $2;`
	
	_, err := db.Exec(updateSQL, newPosition, id)
	if err != nil {
		log.Fatalf("Failed to update position: %v", err)
	}
	fmt.Println("Employee position updated.")
}

// Usage:
// updateEmployeePosition(db, 1, "Senior Developer")

Delete Data

Delete an employee from the database by their ID:

func deleteEmployee(db *sql.DB, id int) {
	deleteSQL := `
	DELETE FROM employees
	WHERE id = $1;`
	
	_, err := db.Exec(deleteSQL, id)
	if err != nil {
		log.Fatalf("Failed to delete employee: %v", err)
	}
	fmt.Println("Employee deleted successfully.")
}

// Usage:
// deleteEmployee(db, 1)

Explanation of Code:

  • Connecting to PostgreSQL: Uses sql.Open with the pq driver to connect to PostgreSQL. Connection details are provided in a formatted string.
  • Executing SQL Statements: CRUD functions execute SQL statements with placeholder parameters (like $1, $2) to prevent SQL injection.
  • Error Handling: Functions log fatal errors for simple debugging and reliability in handling database issues.

Step 5: Close Connection

Remember to close the database connection after your operations:

defer db.Close()

Additional Information:

  • Data Types: Golang has strict types, so ensure that SQL queries and Go code handle types properly.
  • Transactions: Use transactions for multiple operations, particularly if operations depend on each other.
  • Environment Variables: Store credentials in environment variables for secure and dynamic configurations.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/postgresql-golang-guide.php