I'm trying to connect Golang to a Postgres DB, it is in Gcloud and I already allowed the network IP. I'm trying to access the User DB and then the User table inside the public schema, this is the database structure:
I am getting this error: pq: database "Users" does not exist
I'll add the code:
package ports
import (
"database/sql"
"log"
"github.com/gofiber/fiber/v2"
_ "github.com/lib/pq"
)
func OpenConnection(dbName string) (*sql.DB, error) {
connStr := "<addr>" dbName
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
return db, err
}
func GetUsers(ctx *fiber.Ctx) error {
db, dbErr := OpenConnection("Users")
if dbErr != nil {
log.Fatalln(dbErr)
}
defer db.Close()
rows, err := db.Query("SELECT * FROM Users")
if err != nil {
log.Fatalln(err)
ctx.JSON("An error ocurred")
}
defer rows.Close()
return ctx.Render("/users", fiber.Map{
"Users": rows,
})
}
CodePudding user response:
I just fixed it and it was a combination of two things:
- I wasn't properly combining the strings, when I hardcoded it I got rid of the db error.
- After that I encountered an error where it would say the table doesn't exists, the issue is I was sending an unquote table name and I needed it to be case sensitive so I had to wrap the name between quotes to make it work. Like so
package ports
import (
"database/sql"
"log"
"github.com/gofiber/fiber/v2"
_ "github.com/lib/pq"
)
func OpenConnection() (*sql.DB, error) {
connStr := "<connStr>/users"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
return db, err
}
func GetUsers(ctx *fiber.Ctx, db *sql.DB) error {
defer db.Close()
rows, err := db.Query(`SELECT * FROM "Users"`)
if err != nil {
log.Fatalln(err)
ctx.JSON("An error ocurred")
}
defer rows.Close()
return ctx.Render("/users", fiber.Map{
"Users": rows,
})
}