解決Go gorm踩過的坑
使用gorm.Model后無法查詢數(shù)據(jù)
Scan error on column index 1, name “created_at”
提示:
Scan error on column index 1, name “created_at”: unsupported Scan, storing driver.Value type []uint8
解決辦法:
打開數(shù)據(jù)庫的時候加上parseTime=true
root:123456@tcp(127.0.0.1:3306)/mapdb?charset=utf8&parseTime=true
補充:golang Gorm 的使用總結
建立結構體時可以通過 TableName來指定要查找的表名
func (CoinLog) TableName() string {
return "coin_log"
}
通過gorm的映射指定對應表的列
ID int64 `gorm:"column:id" json:"id"`
通過預加載可以實現(xiàn)各個模型之間的一對多關系,例如下面的代碼,其中device結構體對應多個DeviceModular,DeviceModular又有多個CommWeimaqi
通過下面的查詢語句可以查詢出對應的相關聯(lián)數(shù)據(jù)
db.SqlDB.Preload("DeviceModular", "modular_type=1").Preload("DeviceModular.CommWeimaqi").Find(&device)
gorm暫時不支持批量插入
可以通過下面的方式完成批量插入的功能
tx := db.SqlDB.Begin()
sqlStr := "INSERT INTO report_form (id,create_time,choose_count, device_fall_count,game_order_count,coin_count,member_count," +
"day_member_count,visit_count,lgz_coin_count,weimaqi_coin_count,store_id,real_coin_count,m_coin_count,coin_spec) VALUES "
vals := []interface{}{}
const rowSQL = "(?,?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?)"
var inserts []string
for _, elem := range reportForms {
inserts = append(inserts, rowSQL)
vals = append(vals, elem.ID, elem.CreateTime, elem.ChooseCount, elem.DeviceFallCount, elem.GameOrderCount, elem.CoinCount, elem.MemberCount, elem.DayMemberCount, elem.VisitCount, elem.LgzCoinCount, elem.WeimaqiCoinCount, elem.StoreId, elem.RealCoinCount, elem.MCoinCount, elem.CoinSpec)
}
sqlStr = sqlStr + strings.Join(inserts, ",")
err := tx.Exec(sqlStr, vals...).Error
if err != nil {
tx.Rollback()
fmt.Print(err)
}else {
tx.Commit()
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
Go|使用Options模式和建造者模式創(chuàng)建對象實戰(zhàn)
這篇文章主要介紹了Go使用Options模式和建造者模式創(chuàng)建對象實戰(zhàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04

