我在具有以下架构的列中将过期日期插入Postgres:exp DATE NOT NULL
我在Golang中创建这些日期的方式是使用使用Time
数据类型的“时间”库(不确定其基础类型是否为字符串,go docs并未真正指定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
最佳答案
如果我没记错的话,pgx
将DATE
映射到time.Time
。要进行扫描,您要么需要一个指向该指针的指针,要么使用pgx
的pgtype.Date
数据类型(我已经习惯了这些,所以我总是使用它们):
var dt pgtype.Date
err := conn.QueryRow("select exp from items where sub = $1", 1).Scan(&dt)
然后
pgtype.Date
具有一个称为Time
的字段,其类型为time.Time
,因此您应该可以正常使用它。参见documentation。
关于postgresql - 我应该如何将Postgres日期类型分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61410868/