I am trying to insert data into a table which i know is there, as the exact same query works directly on the database
GO CODE:
const (
host = "localhost"
user = "postgres"
password = "postgres"
dbname = "user_details"
)
func connectDb() *sql.DB {
sqlInfo := fmt.Sprintf("host=%s user=%s "+
"password=%s dbname=%s sslmode=disable",
host, user, password, dbname)
db, err := sql.Open("postgres", sqlInfo)
fmt.Fprintf(os.Stdout, "\n%v", sqlInfo)
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Fprintf(os.Stdout, "You have successfully connected to the database")
return db
}
The above code creates the connection which i call in the main func as db = connectDb
setting the global db variable to the db which gets returned from the connectDB function. This appears to work, and connect okay using the built in ping method
The below code is the insert statement ran from the handleRegister
func. I have done checks to make sure the db is still connected which it should be as I have a defer db.Close()
in the main func to close the DB conn when the program exits.
sqlSt := `INSERT INTO users ("User_id", "username", "password", "email", "gender", "gang") VALUES ($1, $2, $3, $4, $5, $6)`
_, err = db.Exec(sqlSt, 1, ud.Username, pw, ud.Email, ud.Gender, ud.Gang)
if err != nil {
panic(err)
}
below are the tables within my database.
Any help appreciated
MININMAL program:
ERROR: Failed to query dbpanic: pq: relation âusersâ does not exist
package main
import (
"database/sql"
"fmt"
"os"
_ "github.com/lib/pq"
)
const (
host = "localhost"
user = "postgres"
password = "postgres"
dbname = "user_details"
)
func main() {
sqlInfo := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", host, user, password, dbname)
db, err := sql.Open("postgres", sqlInfo)
if err != nil {
fmt.Fprintf(os.Stdout, "Connection to the database failed")
return
}
err = db.Ping()
if err != nil {
fmt.Fprintf(os.Stdout, "Connection to the database failed")
return
}
fmt.Fprintf(os.Stdout, "You have connected to the database successfully")
sqlQuery := `INSERT INTO users ("user_id", "username", "password", "email", "gender", "gang") VALUES ($1, $2, $3, $4, $5, $6)`
_, err = db.Exec(sqlQuery, 1, "Ross8839", "rocky8839", "ross88399@hotmail.com", "Female", "Greengos")
if err != nil {
fmt.Fprintf(os.Stdout, "Failed to query db")
panic(err)
}
}