Skip to content
Advertisement

sql golang invalid memory address or nil pointer dereference when do query

i am trying to insert data after the connection, when i command the logic of INSERT... i was able to connect to the database, but when i uncommand them , i got error

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x40f8e2a]

here is my function :

func Connect() (*sql.DB, error) {
    db, err := sql.Open("postgres", os.Getenv("PG_URL"))
    if err != nil {
        return nil, err
    }
    defer db.Close()

    stmt, _ := db.Prepare("INSERT INTO users(name, email, password) VALUES(?,?,?)")
    res, err := stmt.Exec("test", "test@mail.com", "12344")

    if err != nil{
        panic(err.Error())
    }
    fmt.Println(res)
    fmt.Println("Successfully connected!")
    return db, nil
}

I have tried to do the same thing also like this article go sql and have the same issue do I wrong implement this?

Advertisement

Answer

I bet a dollar/euro/frank that the NPE is on the line executing the prepared statement and that if you check the only error you ignored it won’t be nil and it will tell you what’s wrong.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement