如何使用go-sql-driver连接到Amazon RDS

I can connect to the RDS instance using mysql -h ... command so I know it's not a security group problem.

I've tried to use:

sql.Open("mysql", "id:password@tcp(your-amazonaws-uri.com:3306)/dbname")

in the readme file of go-sql-driver(https://github.com/go-sql-driver/mysql), but it doesn't seem to work.

I'm using my username under the RDS instance instead of id here though.

Edit: The error returned is: panic runtime error: invalid memory address or nil pointer deference [signal 0xb code=0x1 addr=0x20 pc=0x5b551e] goroutine 16 [running] runtime.panic(0x7d4fc0, 0xa6ca73)...database/sql.(*Rows).Next...

It works fine with my local DB.

Make sure the actual error isn't related to an import issue (as in issues 266)

Check (to be sure you are using the latest versions, as in this issue):

  • your Go-MySQL-Driver version (or git SHA)
  • your Go version (run go version in your console)

If the error isn't directly in the Open step, but when accessing the Rows, check this comment out:

Use either a for loop (for rows.Next() { ... }) or something like this:

if rows.Next() {
     // whatever
} else {
     // catch error with rows.Err()
}
rows.Close() // <- don't forget this if you are not iterating over ALL results

The connection string for sql.Open() is in DSN format.

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

db, err := sql.Open("mysql", "<username>:<password>@tcp(<AWSConnectionEndpoint >:<port>)/<dbname>")

if err != nil {
    fmt.Print(err.Error())
}

defer db.Close()