postgresql - 如何在 Postgres 表上存储 Go 的当前时间(小时-分钟-秒)?

标签 postgresql go

我想通过 Go 将用户 checkin 和 checkout 时间(小时、分钟和秒)存储在 Postgres 表中(列类型当然是 time)

query := `INSERT INTO oc_log (userid, userdate, checkin_time, checkin_location, checkout_time, checkout_location) VALUES ($1, $2, $3, $4, $5, $6)`

err := db.QueryRow(query, userid, time.Now().Format("01-02-2006"), time.Now().Clock(), checkinlocation, "", "").Scan(&tmpid)

go linter 提示说

multiple-value time.Now().Clock() in single-value context

如何解决这个问题?

最佳答案

只需使用time.Time 值,让驱动程序担心如何编码和解码它们:

package main

import (
    "database/sql"
    "fmt"
    "log"
    "time"

    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "")
    if err != nil {
        log.Fatal(err)
    }

    _, err = db.Exec("CREATE TABLE foo (t timetz)")
    if err != nil {
        log.Fatal(err)
    }

    now := time.Now()
    _, err = db.Exec("INSERT INTO foo VALUES ($1)", now)
    if err != nil {
        log.Fatal(err)
    }

    var t time.Time
    err = db.QueryRow("SELECT t FROM foo").Scan(&t)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(now.Format(time.RFC3339)) // 2019-09-18T10:22:36+02:00
    fmt.Println(t.Format(time.RFC3339))   // 0000-01-01T10:22:36+02:00
}

关于postgresql - 如何在 Postgres 表上存储 Go 的当前时间(小时-分钟-秒)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57987718/

相关文章:

go - 是否有工具可以检测我何时忘记关闭 goroutines?

go - 如何将 Go 中间件模式与错误返回请求处理程序结合起来?

postgresql - 使用 postgresql/snowflake 提取 json 键/值对,其中值不为 null/空白

json - 如何使一个空的 JSON 对象在 Postgres 中不唯一?

oracle - 相当于 postgres 中 Oracle 的 pragma autonomous_transaction

go - BOX/JWT OAuth 2.0 由 golang

go - 如何将包含错误对象的 reflect.Value 分配给错误类型的普通变量?

postgresql - 如何在 docker-compose up 时创建 postgres 数据库并运行迁移

python - 如何关闭我在线程中使用的 Flask-SQLAlchemy 连接?

go - 检查 Go 中的结构类型