sqlx: runtime error: invalid memory address or nil pointer dereference

1.1k Views Asked by At

I'am learning to use sqlx,but now I have a problem.

[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x7006c8]

goroutine 1 [running]:
github.com/jmoiron/sqlx.(*DB).QueryRowx(0x0, {0x75cb6a, 0x22}, {0xc000090c70, 0x1, 0x1})

This is my code and I don't know why this error occurring. import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" )

var DB *sqlx.DB

func initializeDatabases() (err error) {
    dsn := "user:password@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True"
    DB, err := sqlx.Connect("mysql", dsn)
    if err != nil {
        fmt.Printf("connect 2 dtatbase failed,err:%v\n", err)
        return
    }
    DB.SetMaxOpenConns(10)
    DB.SetMaxIdleConns(10)
    return err
}

func sqlxQuerySingleRow() {
    sqlStr := "select * from student where id = ?"
    var u User
    if err := DB.Get(&u, sqlStr, 1); err != nil {
        return
    }
    fmt.Println("id:%d,name:%s,age:%d", u.Id, u.Name, u.Age)

}

func main() {
    if err := initializeDatabases(); err != nil {
        panic(err)
    }
    fmt.Println("connect  success")
    sqlxQuerySingleRow()
    //sqlxMultiRow()
}
1

There are 1 best solutions below

0
On

I know why,because I defined the DB as a global variable,but in the initializeDatabases() function,I declared the DB by:= which causes the returned Client connection to only take effect in the initializeDatabases()function,so I should change:= to =