dtmu88600 2016-01-29 17:25
浏览 122
已采纳

不会从Go sqlx库加载struct Time属性

I have a struct with a property time:

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

with the time saved as:

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

If I save it using Insert sql statement, it saves the time nicely in the SQLite3 but when I select the desired record using:

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

It returns the record with other properties loaded properly except the time property which is ret_basket.Created_at as 0001-01-01 00:00:00 +0000 UTC

Any suggestions?

  • 写回答

1条回答 默认 最新

  • duancanjiu3754 2016-01-29 19:48
    关注

    There is no official package for Sqlite so I assume you are using https://github.com/mattn/go-sqlite3 Probably your issue is result of wrong created_at field declaration in database which should be DATETIME because the next code works perfectly on my machine (I've removed all error checks):

    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"))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误