Sobes.tech
Junior — Middle

How is connection to a remote database for reading or writing data established?

sobes.tech AI

Answer from AI

In Go, connecting to a remote database is usually done through the database/sql package along with a driver for the specific DBMS.

Example of connecting to PostgreSQL:

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

func main() {
    connStr := "user=username password=secret dbname=mydb host=remotehost port=5432 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(err)
    }

    // Now you can perform queries
}

Here, sql.Open creates a connection object, and db.Ping() checks the database's availability. After that, you can use methods like Query, Exec for reading and writing data.

How is connection to a remote database for reading or… - sobes.tech