[SOLVED] What is the scenario for getting error "dial tcp xxx:xxx:xxx:xxx:3306: connect: connection refused" and how to avoid this error


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:%[email protected](%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() {
        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]


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

Answered By – Tiago Peczenyj

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *