commands out of sync. did you run multiple statements at once

阅读 101

2022-08-12


问题

数据库在执行几次插入操作后导致数据库连接错误,抛出错误
commands out of sync. did you run multiple statements at once

原因

  1. 首先正常插入操作可以排除连接参数问题
  2. 检查发现数据库由于多次插入操作导致此处open了过多的数据库连接。
  3. commands out of sync. did you run multiple statements at once_数据库

解决

定义全局的数据库连接,即同一个连接多次使用

定义一个公共的变量

var (
DB *gorm.DB
)

定义一个建立连接的函数

func GetDB() (*gorm.DB,error) {
dsn := "root:root@tcp(127.0.0.1:3306)/trs_hycloud_igi?charset=utf8&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
return db, err
}

在主函数中调用建立连接的函数并对定义的公共的变量赋值

func main() {
service.DB,_= service.GetDB()
}

其他数据库操作可直接使用公共变量操作

:= DB
db.Create(&reply)


精彩评论(0)

0 0 举报