如何解决Go gorm踩过的坑

发布时间:2021-05-06 10:17:00 作者:小新
来源:亿速云 阅读:563

这篇文章给大家分享的是有关如何解决Go gorm踩过的坑的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

什么是go

go是golang的简称,golang 是Google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言,其语法与 C语言相近,但并不包括如枚举、异常处理、继承、泛型、断言、虚函数等功能。

使用gorm.Model后无法查询数据

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

解决办法:

打开数据库的时候加上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"`

通过预加载可以实现各个模型之间的一对多关系,例如下面的代码,其中device结构体对应多个DeviceModular,DeviceModular又有多个CommWeimaqi

通过下面的查询语句可以查询出对应的相关联数据

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踩过的坑”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. Go语言gdb调试踩坑
  2. go语言中的orm

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

go gorm

上一篇:Go语言中go程释放操作的示例分析

下一篇:Java如何实现双色球彩票小游戏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》