溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何解決Go gorm踩過的坑

發(fā)布時間:2021-05-06 10:17:00 來源:億速云 閱讀:604 作者:小新 欄目:開發(fā)技術

這篇文章給大家分享的是有關如何解決Go gorm踩過的坑的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

什么是go

go是golang的簡稱,golang 是Google開發(fā)的一種靜態(tài)強類型、編譯型、并發(fā)型,并具有垃圾回收功能的編程語言,其語法與 C語言相近,但并不包括如枚舉、異常處理、繼承、泛型、斷言、虛函數(shù)等功能。

使用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()
  }

感謝各位的閱讀!關于“如何解決Go gorm踩過的坑”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI