2016-01-29 32 views
2

我有一個屬性的時間結構:結構的時間屬性不從根本SQLX庫加載

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

與時間存爲:

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

如果我保存使用插入SQL它聲明中,它很好地節省時間在sqlite3的,但是當我選擇使用所需的記錄:

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

它返回一個記錄其他性能正常加載除了時間屬性是ret_basket.Created_at0001-01-01 00:00:00 +0000 UTC

任何建議?

回答

3

沒有官方包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")) 
}