Home > OS >  Unable to open tcp connection. No connection could be made because the target machine actively refus
Unable to open tcp connection. No connection could be made because the target machine actively refus

Time:11-10

I tried to fetch data from a SQL Server database. When I run, it keeps giving me this error:

unable to open tcp connection with host 'localhost:1433': dial tcp [::1]:1433: connectex: No connection could be made because the target machine actively refused it.
exit status 1


My code:

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/denisenkom/go-mssqldb"
)

var kiosk string

var server = ".\\MSSQLSERVER01"
var port = 1433
var user = "DESKTOP-37624KK"
var password = "**********"
var database = "Kiosk"

func main() {
    connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s", server, user, password, port, database)

    db, err := sql.Open("mssql", connString)
    if err != nil {
        fmt.Println("Error in connect DB")
        log.Fatal(err)
    }

    rows, err := db.Query("SELECT * FROM Kiosk")
    if err != nil {
        log.Fatal(err)
    }

    for rows.Next() {
        if err := rows.Scan(&kiosk); err != nil {
            log.Fatal(err)
        }
        fmt.Println(kiosk)
    }
    defer rows.Close()
}

  • Checked if firewall is blocking needed port
  • Tried to change and connect to new ports
  • Tried to search on the internet for other solutions. Nothing has helped yet

CodePudding user response:

The server variable value is wrong. The dot (.) means "localhost". If the SQL server is installed locally just use "." (or ".\InstanceName" - if there are multiple instances installed). If the server is installed in the network just use SERVERNAME (without the leading backslashes), or SERVERNAME\InstanceName.

  • Related