【问题标题】:How should I assign Postgres date type to a variable我应该如何将 Postgres 日期类型分配给变量
【发布时间】:2020-04-25 03:23:33
【问题描述】:

我正在将过期日期插入 Postgres 中具有以下架构的列中:
exp DATE NOT NULL

我在 Golang 中创建这些日期的方式是使用使用 Time 数据类型的“时间”库(不确定它的基础类型是否是字符串,go 文档并没有真正指定 see here )。

这是我使用pgx 库进行插入的方法

expirationDate := time.Unix(expiresAt, 0)
sql := `
  insert into items 
  (sub, uuid, exp) 
  VALUES ($1, $2, $3)
`
_, err := connection.Exec(
  context.Background(),
  sql,
  subject,
  id,
  expirationDate,
)

我的代码expiresAt 的其他地方是这样制作的:

days := 1 * 24 * time.Hour
expirationTime := time.Now().Add(days)
expirationTime.Unix() // this is what's being passed in my function (expiresAt int64) that does the DB insertion

问题是试图从 Postgres 中恢复该日期。
当我在 pgAdmin 中查看它时,我看到它被存储为 yyyy-mm-dd 所以我想也许我可以将它分配给一个字符串变量,所以我尝试了这个:

type RevokedRefreshToken struct {
  OldUUID           string
  OldExpirationDate string
}
var revokedRefreshToken RevokedRefreshToken
err := connection.QueryRow(context.Background(), "select uuid, exp from items where sub = $1", subject).
Scan(&revokedRefreshToken.OldUUID, &revokedRefreshToken.OldExpirationDate)

我也试过了:
- int64 类型
- 时间类型
- 不使用其内存地址传递它(Scan() 中没有 &)

我仍然无法确定要将此数据库值分配给的数据类型。
这是我认为来自 pgx 的错误: can't scan into dest[1]: unable to assign to *string

我需要使用什么数据类型来分配 PostgreSQL date type 的这个 DB 值

【问题讨论】:

    标签: postgresql go


    【解决方案1】:

    如果我没记错的话 pgx 映射 DATEtime.Time。要进行扫描,您要么需要指向指针的指针,要么使用 pgxpgtype.Date 数据类型(我已经习惯了这些,所以我总是使用它们):

    var dt pgtype.Date
    err := conn.QueryRow("select exp from items where sub = $1", 1).Scan(&dt)
    

    pgtype.Date 有一个名为Time 的字段,其类型为time.Time,因此您应该能够正常使用它。见documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多