如何在Postgresql时间戳中存储Golang time.time?

Boo*_*ong 2 postgresql go

我可以知道如何time.time在Postgresql中存储对象吗?

例如,SQL查询:

INSERT INTO "UserAccount" ("email", "login_time") VALUES ('human@example.com', 2017-12-12 00:58:26.9589451 +0800 +08 m=+1406.914186601)

我尝试使用loginTime := time.Now(),它给出了Postgresql不太懂的时间格式,例如2017-12-12 00:58:26.9589451 +0800 +08 m = + 1406.914186601

但是,如果我尝试使用loginTime := time.Now().Format(time.RFC3339),并且编译器抱怨这loginTime是一个string,我需要它是time.time类型.

我可以知道如何处理吗?

很抱歉提出新手问题,Golang和Postgres都是新手.:)

mae*_*ics 8

您应该使用sql#DB.Exec(...)占位符参数,而不是手动构建查询字符串,以便数据库驱动程序正确地为您转义值.这样做是最好的做法,特别是为了避免SQL注入等安全错误.

email, loginTime := "human@example.com", time.Now()
result, err := db.Exec("INSERT INTO UserAccount VALUES ($1, $2)", email, loginTime)
if err != nil {
  panic(err)
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,Postgres不支持`?`占位符。您必须使用`$ 1`和`$ 2`,或使用类似[sqlx](https://github.com/jmoiron/sqlx)的`Rebind()`函数。 (4认同)

Dav*_*rth 7

pq 驱动程序(我假设您正在使用)自动为您正确转换 time.Time 实例。

所以,你可以这样做:

db.Exec(`INSERT INTO "UserAccount" ("email", "login_time") VALUES ($1, $2)`,"human@example.com",time.Now())
Run Code Online (Sandbox Code Playgroud)