5

我有一个带有时间属性的结构:

type Basket struct {  
  ...  
  Created_at time.Time `db:"created_at"`
}

时间保存为:

basket.Created_at = time.Now().UTC()

如果我使用 Insert sql 语句保存它,它可以很好地节省 SQLite3 中的时间,但是当我使用以下命令选择所需的记录时:

ret_basket := Basket{}
err := database.DB.Get(&ret_basket, "SELECT id, ..., created_at FROM baskets WHERE user_id = ?", some_user_id)

它返回具有正确加载的其他属性的记录,除了 time 属性ret_basket.Created_at0001-01-01 00:00:00 +0000 UTC

有什么建议么?

4

1 回答 1

4

Sqlite 没有官方软件包,所以我假设您使用的是https://github.com/mattn/go-sqlite3可能您的问题是created_at数据库中错误字段声明的结果,这应该是DATETIME因为下一个代码在我的机器上完美运行(我已删除所有错误检查):

package main

import (
    "github.com/jmoiron/sqlx"
    _ "github.com/mattn/go-sqlite3"
    "log"
    "time"
)

type Post struct {
    Id      int64     `db:"post_id"`
    Created time.Time `db:"created"`
}

func main() {
    db, _ := sqlx.Connect("sqlite3", "post_db.db")
    db.MustExec("DROP TABLE IF EXISTS posts; CREATE TABLE posts (post_id INT, created DATETIME);")

    p1 := Post{Id: 1, Created: time.Now().UTC()}
    p2 := Post{}

    tx := db.MustBegin()
    tx.NamedExec("INSERT INTO posts (post_id, created) VALUES (:post_id, :created)", &p1)
    tx.Commit()

    db.Get(&p2, "SELECT post_id, created FROM posts WHERE post_id = $1", p1.Id)
    log.Println(p2.Created.Format("2006-01-02"))
}
于 2016-01-29T19:48:39.960 回答