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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47758359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:40:30  来源:igfitidea点击:

How to store Golang time.time in Postgresql timestamp?

postgresqlgo

提问by Boo Yan Jiong

May I know how to store the time.timeobject in Postgresql?

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

For example, the SQL query:

例如,SQL 查询:

INSERT INTO "UserAccount" ("email", "login_time") VALUES ('[email protected]', 2017-12-12 00:58:26.9589451 +0800 +08 m=+1406.914186601)

INSERT INTO "UserAccount" ("email", "login_time") VALUES ('[email protected]', 2017-12-12 00:58:26.9589451 +0800 +08 m=+1406.914186601)

I tried to use loginTime := time.Now(), and it gives a time format that Postgresql don't really understand, e.g. 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

But if I try to use loginTime := time.Now().Format(time.RFC3339), and the compiler complain that loginTimeis a string, and I need it to be time.timetype.

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

May I know how to handle this?

我可以知道如何处理吗?

Sorry for asking newbie question, new to both Golang and Postgres. :)

很抱歉问新手问题,Golang 和 Postgres 都是新手。:)

回答by maerics

Instead of manually building the query string you should use sql#DB.Exec(...)with placeholder parameters so that the database driver properly escapes the values for you. Doing it this way is a best-practice, especially to avoid security errors such as SQL injection.

您应该使用sql#DB.Exec(...)占位符参数而不是手动构建查询字符串,以便数据库驱动程序正确地为您转义这些值。这样做是最佳实践,尤其是为了避免诸如SQL 注入之类的安全错误。

email, loginTime := "[email protected]", time.Now()
result, err := db.Exec("INSERT INTO UserAccount VALUES (, )", email, loginTime)
if err != nil {
  panic(err)
}

回答by David Budworth

The pq driver (which I assume you are using) automatically converts time.Time instances correctly for you.

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

so, you can do:

所以,你可以这样做:

db.Exec(`INSERT INTO "UserAccount" ("email", "login_time") VALUES (, )`,"[email protected]",time.Now())