I want to use a PostgreSQL database from a Go webserver, and as a first step I just want basic access to the database. I can create a table, and add a record, but on retrieval f said record, Go chokes on the timestamp.
2023/05/24 14:15:36 sql: Scan error on column index 3, name “created_at”: unsupported Scan, storing driver.Value type into type *time.Time
This is the line it is failing at.
if err := db.QueryRow(query, 1).Scan(&id, &username, &password, &createdAt); err != nil {
I have found mention of an issue with MySQL that involves setting something in the connection string ( parseTime=true
), but nothing for Postgres. I am only just starting out with Go, and most of my code is copied from elsewhere - and that uses MySQL.
package main
import (
"database/sql"
"fmt"
"log"
"time"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "*******"
dbname = "com_dev"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
log.Fatal(err)
}
if err := db.Ping(); err != nil {
log.Fatal(err)
}
{ // Create a new table
fmt.Println("Trying to create user table")
query := `
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username TEXT NOT NULL,
password TEXT NOT NULL,
created_at TIMESTAMP
);`
if _, err := db.Exec(query); err != nil {
fmt.Println(err)
//log.Fatal(err)
}
}
{ // Insert a new user
fmt.Println("Trying to add user")
username := "johndoe"
password := "secret"
createdAt := time.Now()
result, err := db.Exec("INSERT INTO users (username, password, created_at) VALUES ($1, $2, $3)", username, password, createdAt)
if err != nil {
fmt.Println("add failed")
log.Fatal(err)
}
id, err := result.LastInsertId()
fmt.Println(id)
}
{ // Query a single user
fmt.Println("Trying to find user")
var (
id int
username string
password string
createdAt time.Time
)
query := "SELECT id, username, password, created_at FROM users WHERE id = $1"
if err := db.QueryRow(query, 1).Scan(&id, &username, &password, &createdAt); err != nil {
log.Fatal(err)
}
fmt.Println(id, username, password, createdAt)
}
}