I have a simple program:
package main
import (
"database/sql"
"log"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", "user=demas password=pass host=192.168.99.100 port=32768 dbname=mydb sslmode=disabled")
if err != nil {
log.Fatal(err)
}
var name string
rows, err := db.Query("select name from films")
for rows.Next() {
err = rows.Scan(&name)
if err != nil {
log.Fatal(err)
}
log.Printf("Subject is %s", name)
}
}
When I try to run it I get the error:
λ go run main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x20 pc=0x460b2d]
goroutine 1 [running]:
panic(0x5d02a0, 0xc0420040c0)
G:/scoop/apps/go/1.7.1/src/runtime/panic.go:500 +0x1af
database/sql.(*Rows).Next(0x0, 0x607fa6)
G:/scoop/apps/go/1.7.1/src/database/sql/sql.go:1752 +0x2d
main.main()
D:/dev_experiments/go-db1/main.go:18 +0x116
exit status 2
How can I fix it ?
As hobbs said, you're not checking the error on your db.Query.
Also, defer a db.Close() after you check errors there. Make sure to check an error before you preform any action on rows. If it returns an error, you're not going to also get a 'rows' back. So rows is nil.