Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to mysql database with go

Tags:

mysql

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
like image 679
Jacobm001 Avatar asked Sep 11 '13 23:09

Jacobm001


1 Answers

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?
like image 121
Jimmy Sawczuk Avatar answered Oct 23 '22 04:10

Jimmy Sawczuk