我应该如何将Postgres日期类型分配给变量



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

我在Golang中创建这些日期的方式是使用"时间"库,该库使用Time数据类型(不确定其基础类型是否为字符串,go文档并没有真正指定,请参阅此处(。

以下是我如何使用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类型
-时间类型
-不使用内存地址(没有扫描((中的&(传递它

我仍然无法确定应该将此DB值分配给的数据类型。
以下是我从pgx中得到的错误:can't scan into dest[1]: unable to assign to *string

我需要使用什么数据类型来分配PostgreSQL日期类型的DB值

如果我没记错,pgx会将DATE映射到time.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,所以您应该能够正常使用它。请参阅文档。

相关内容

最新更新