.Maui Blog

Connect to a Sql Server database with Go

In this example, let’s see how to connect to Sql Server, select and view the database version using Go programming language.

package main

import (
    _ "github.com/denisenkom/go-mssqldb"
    "database/sql"
    "context"
    "log"
    "fmt"
)

// Replace with your own connection parameters
var server = "MY_SERVER"
var port = 1433
var user = "MY_USERNAME"
var password_mssql = "MY_PASSWORD"

var db *sql.DB

func main() {
    var err error

    // Connection string
    connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d",
        server, user, password_mssql, port)

    // Connection pool
    db, err = sql.Open("sqlserver", connString)
    if err != nil {
        log.Fatal("Error creating connection pool: " + err.Error())
    }
    log.Printf("Connected!\n")
    
    // Close connection pool
    defer db.Close()

    ctx := context.Background() 
    err = db.PingContext(ctx)
    if err != nil {
        log.Fatal("Error pinging database: " + err.Error())
    }

    var result string

    // Run query and scan for result
    err = db.QueryRowContext(ctx, "SELECT @@version").Scan(&result)
    if err != nil {
        log.Fatal("Scan failed:", err.Error())
    }
    fmt.Printf("%s\n", result)
}


Exit mobile version