Home > other >  What is the scenario for getting error "dial tcp xxx:xxx:xxx:xxx:3306: connect: connection refu
What is the scenario for getting error "dial tcp xxx:xxx:xxx:xxx:3306: connect: connection refu

Time:03-22

I have a api which is calling the sql connection. This is sql connection to some remote server. While performing a query I am getting error "dial tcp xxx:xxx:xxx:xxx:3306: connect: connection refused"

Sql connection code

func ConnectToMysqlDB(dbUser, dbPassword, dbHost, dbName string) *sql.DB {
    connstr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPassword, dbHost, "3306", dbName)
    var err error
    log.Println("Carrying mysql query", connstr)
    dB, err := sql.Open("mysql", connstr)
    if err != nil {
        log.Fatalf("error connection to mysql [%v] ..!!", err)
    }
    log.Print("mysql initialized ..!!")
    return dB
}

Query function

func GetUserIDs(dB *sql.DB, users []string) []int {
    var newUsers []int
    var newUser int

    query := "SELECT id FROM phplist_user_user WHERE foreignkey in (%s)"
    var usersStr string
    for _, val := range users {
        usersStr = usersStr   "'"   val   "'"   ","
    }
    usersStr = strings.TrimSuffix(usersStr, ",")

    query = fmt.Sprintf(query, usersStr)

    rows, err := dB.Query(query)
    if err != nil {
        fmt.Printf("Error in query : [%v]", err)
    }
    defer rows.Close()
    for rows.Next() {
        rows.Scan(&newUser)
        newUsers = append(newUsers, newUser)
    }

    return newUsers
}

what is the sceario where I am getting the error: Error in query : [dial tcp xxx.xxx.xxx.xxx:3306: connect: connection refused]

This is the api:- https://go.dev/play/p/sXDLb7vTXQr

CodePudding user response:

My two cents:

  1. Validate if you are really connected to mysql using the Ping() method in sql.DB — however you must pay attention that some errors may be temporary. For instance if you have a network issue or a database “reboot” (high availability depends of many factors)
  2. Check if you are using the right ip and port. Perhaps the database and application are in different networks or the database server binds more than one network card.

Also, Check if this helps https://github.com/go-sql-driver/mysql#allowcleartextpasswords

  • Related