Sobes.tech
Junior — Middle

Kuidas toimub ühendus kaugarvutuse andmebaasiga andmete lugemiseks või kirjutamiseks?

sobes.tech AI

Vastus AI-lt

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

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 Query, Exec methods to read and write data.