Extending sqlx GetRow Gives Invalid Memory Address or Nil Pointer Exception


I cant find the reason of error in the following code. It runs successful if I use sqlx.Get directly. Do you have any idea?

package main

import (
	_ "github.com/go-sql-driver/mysql"

type Product struct {
	Id int64 `db:"productid" json:"id"`

var db *sqlx.DB

func main() {

	var p Product

	q := "SELECT productid FROM l_product "

	db, err := sqlx.Open("mysql", "getiriver:getiriver@tcp(localhost:3306)/getiriver?charset=utf8")
	if err != nil {
	defer db.Close()

	err = GetRow(&p, q)

	if err != nil {



func GetRow(target interface{}, q string) error {

	err := db.Get(target, q)
	if err != nil {
		return err

	return nil


end the error is

C:\Go\work\src\github.com\ligaci\test>go run test.go
SELECT productid FROM l_product
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x594d1d]

goroutine 1 [running]:
github.com/jmoiron/sqlx.(*DB).QueryRowx(0x0, 0x600b90, 0x20, 0x0, 0x0, 0x0, 0x5)
        C:/Go/work/src/github.com/jmoiron/sqlx/sqlx.go:355 +0x2d
github.com/jmoiron/sqlx.Get(0x6bd820, 0x0, 0x5ae660, 0xc04203a690, 0x600b90, 0x20, 0x0, 0x0, 0x0, 0x0, ...)
        C:/Go/work/src/github.com/jmoiron/sqlx/sqlx.go:675 +0x74
github.com/jmoiron/sqlx.(*DB).Get(0x0, 0x5ae660, 0xc04203a690, 0x600b90, 0x20, 0x0, 0x0, 0x0, 0x429555, 0xc042056030)
        C:/Go/work/src/github.com/jmoiron/sqlx/sqlx.go:320 +0x97
main.GetRow(0x5ae660, 0xc04203a690, 0x600b90, 0x20, 0xc042060480, 0x0)
        C:/Go/work/src/github.com/ligaci/test/test.go:43 +0x15b
        C:/Go/work/src/github.com/ligaci/test/test.go:28 +0x14b
exit status 2
db, err := sqlx.Open("mysql", "getiriver:getiriver@tcp(localhost:3306)/getiriver?charset=utf8")

shadows db in main instead of using the global db. This means the global db, used by GetRow, was never set

Instead, write:

var err error
db, err = sqlx.Open("mysql", "getiriver:getiriver@tcp(localhost:3306)/getiriver?charset=utf8")

It works!!

Thank you very much. I was working about it last 2 days.

Shadowed variables can checked using go tool vet -shadow .

In this case, it outputs:

test.go:23: declaration of "db" shadows declaration at test.go:15

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.