查询用户时遇到困难,定义如下:
type User struct { ID int `db:"id" json:"id"` UserName string `db:"username" json:"username"` Email string `db:"email" json:"email"` CreatedAt time.Time `db:"created_at" json:"created_at"` StatusID uint8 `db:"status_id" json:"status_id"` Deleted uint8 `db:"deleted" json:"deleted"` ... }
MariaDB中的表定义为:
+--------------+------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+------------------+------+-----+-------------------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | username | varchar(50) | NO | | NA | | | email | varchar(255) | NO | | NULL | | | created_at | datetime | NO | | CURRENT_TIMESTAMP | | | status_id | tinyint(1) | NO | | 0 | | | deleted | tinyint(1) | NO | | 0 | | ... |
但是,当我查询它时:
func GetUsers(c *gin.Context) { var users []model.User err := shared.Dbmap.Select(&users, "SELECT * FROM user") if err == nil { c.JSON(200, users) } else { fmt.Println("%v \n", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "no user(s) in the table or problem in the query"}) } // curl -i http://127.0.0.1:8080/api/v1/users }
我收到此错误:
sql: Scan error on column index 3: unsupported Scan, storing driver.Value type []uint8 into type *time.Time
虽然表中有一些行.
我也试图created_at
为 timestamp
,但仍然得到同样的错误.
所以我不知道这里有什么不对吗?我该如何解决?
PS虽然我的问题与此有相同的答案,但这里的背景不同(sqlx
而不是go-sql-driver/mysql
).此外,由于错误是主题,它可能更适合谷歌相同的错误的人.所以这或许值得作为一个单独的问题保留.
好吧,我找到了解决方案,谢谢这个答案.问题在于添加?parseTime=true
到db mapper.像这样:
db, err := sqlx.Connect("mysql", "myuser:mypass@tcp(127.0.0.1:3306)/mydb?parseTime=true")