Working with Databases in Go: PostgreSQL and MongoDB for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with Databases in Go: PostgreSQL and MongoDB for Beginners



Go (Golang) is a modern compiled language that has gained popularity due to its high performance, simplicity, and built-in concurrency support. When developing web services and applications, the need to interact with databases almost always arises. In this article, we will look at how to work with two popular DBMS: relational PostgreSQL and document-oriented MongoDB. The material is aimed at beginner developers who are already familiar with the basics of Go.



1. Environment Setup and Driver Installation



Before you begin, make sure you have Go (version 1.16+) installed and the corresponding DBMS running. To work with PostgreSQL, you will need the lib/pq driver, and for MongoDB, the official mongo-go-driver driver.



go get github.com/lib/pqgo get go.mongodb.org/mongo-driver/mongo


Create a new module:



go mod init example.com/db-demo


2. Working with PostgreSQL in Go



PostgreSQL is a powerful relational database with SQL support. In Go, we use the standard database/sql package together with the lib/pq driver.



2.1 Connecting to the Database



To connect, you need to specify the connection string (DSN) in the format: host=... port=... user=... password=... dbname=... sslmode=disable.



package main

import ( "database/sql" "fmt" "log" _ "github.com/lib/pq")

func main() { connStr := "host=localhost port=5432 user=postgres password=secret dbname=testdb sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { log.Fatal(err) } defer db.Close()

err = db.Ping() if err != nil { log.Fatal("Failed to connect:", err) } fmt.Println("Connection to PostgreSQL established!")}


2.2 Creating a Table and CRUD Operations



Let's look at creating a users table and performing basic operations.



// Creating a tablecreateTable := `CREATE TABLE IF NOT EXISTS users (    id SERIAL PRIMARY KEY,    name VARCHAR(100) NOT NULL,    email VARCHAR(100) UNIQUE NOT NULL,    age INT);`

_, err = db.Exec(createTable)if err != nil { log.Fatal(err)}

// Inserting datasqlInsert := `INSERT INTO users (name, email, age) VALUES ($1, $2, $3) RETURNING id`var userID interr = db.QueryRow(sqlInsert, "Ivan Petrov", "ivan@example.com", 30).Scan(&userID)if err != nil { log.Fatal(err)}fmt.Printf("User added with ID: %d", userID)

// Querying datarows, err := db.Query("SELECT id, name, email, age FROM users")if err != nil { log.Fatal(err)}defer rows.Close()

for rows.Next() { var u struct { ID int Name string Email string Age int } err := rows.Scan(&u.ID, &u.Name, &u.Email, &u.Age) if err != nil { log.Fatal(err) } fmt.Printf("ID: %d, Name: %s, Email: %s, Age: %d", u.ID, u.Name, u.Email, u.Age)}


2.3 Using Prepared Statements



Prepared statements improve security and performance, especially for repetitive operations.



stmt, err := db.Prepare("UPDATE users SET age = $1 WHERE id = $2")if err != nil {    log.Fatal(err)}defer stmt.Close()

_, err = stmt.Exec(35, 1)if err != nil { log.Fatal(err)}fmt.Println("User age updated")


3. Working with MongoDB in Go



MongoDB is a NoSQL document-oriented database. In Go, work with it is done through the official mongo-go-driver driver, which uses contexts to manage operation execution time.



3.1 Connecting to MongoDB



pa                

Blogs

Book Recommendations