Jacobm001
Jacobm001

Reputation: 4539

Connecting to mysql database with go

I'm trying to get a basic connect to my mysql server, but I can't seem to get it to actually connect. I know the credentials are valid and have all the permissions they need, but for some reason they're consistently rejected.

package main

import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "os"
)

func main() {
    db, err:= sql.Open("mysql", "user:pass@tcp(localhost:3306)/scf")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    q, err := db.Prepare("SELECT * from logins limit 5")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    rows, err := q.Query()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    i := 0

    for rows.Next() {
        i++
        var title string
        err = rows.Scan( &title )
        fmt.Printf("Title: %s \n", title)
    }

    db.Close()

}

Edit:

Apparently I forgot to include the error:

dial tcp 127.0.0.1:3306: connection refused
exit status 1

Upvotes: 7

Views: 6832

Answers (2)

Somit Srivastava
Somit Srivastava

Reputation: 11

I faced a similar issue. I found out port was different on Mac. I Couldn't find it in my.cnf but the port was set during runtime which you can see using

ps ax | grep mysql

Upvotes: 0

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

connection refused generally means the port isn't open or is being blocked by a firewall. A couple things to check:

  • Is MySQL (on localhost) running? Is it on port 3306?
  • If you're on Windows, Mac or Linux, is there a firewall that might be blocking port 3306?
  • If you're on Linux, is SELinux enabled that might be blocking port 3306?

Upvotes: 3

Related Questions