Junior — Middle
How does the microservice interact with the database for storing and retrieving data?
sobes.tech AI
Answer from AI
A microservice in Go interacts with a database through drivers or ORM libraries that implement an interface for connecting, executing queries, and processing results.
Main steps:
- Establishing a connection to the database using a package like
database/sqland the appropriate driver (e.g.,pqfor PostgreSQL). - Executing SQL queries for inserting, updating, deleting, or selecting data.
- Processing query results and converting them into the required data structures.
Example of connecting and querying a PostgreSQL database:
import (
"database/sql"
_ "github.com/lib/pq"
"log"
)
func getUserByID(db *sql.DB, id int) (string, error) {
var name string
err := db.QueryRow("SELECT name FROM users WHERE id = $1", id).Scan(&name)
if err != nil {
return "", err
}
return name, nil
}
func main() {
connStr := "user=username dbname=mydb sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
defer db.Close()
name, err := getUserByID(db, 1)
if err != nil {
log.Println("Error fetching user:", err)
} else {
log.Println("User name:", name)
}
}
Thus, the microservice uses standard libraries and drivers to interact with the database.