golang pq timestamp
package main
import (
"database/sql"
"fmt"
"log"
"time"
_ "github.com/lib/pq"
)
func main() {
connStr := "user=myuser password=mypassword dbname=mydb sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
log.Fatal(err)
}
timestamp := time.Now()
_, err = db.Exec("INSERT INTO my_table (timestamp_column) VALUES ($1)", timestamp)
if err != nil {
log.Fatal(err)
}
fmt.Println("Timestamp inserted successfully!")
}
This Go code demonstrates connecting to a PostgreSQL database using the database/sql
package and github.com/lib/pq
driver. It establishes a connection, performs a Ping to verify connectivity, generates a timestamp using time.Now()
, and then executes an SQL INSERT
statement to insert the generated timestamp into a table named my_table
in the specified database mydb
. If any error occurs during these steps, it will be logged. Finally, a success message is printed if the timestamp insertion is successful.