最近用 gin+mysql編寫web工程,其中使用了gorm庫對數(shù)據(jù)庫進(jìn)行操作。由于gorm目前暫未提供 批量插入方法,推薦使用原sql語句批量插入數(shù)據(jù)。
參考鏈接
- gorm中文文檔:https://jasperxu.github.io/gorm-zh/
- mysql批量更新與插入相關(guān)博客:https://blog.yumaojun.net/2017/06/19/mysql-performance-for-bulk-action/
批量插入mysql數(shù)據(jù)
// 聲明project_pics數(shù)據(jù)表結(jié)構(gòu)
type ProjectPic struct {
Id int `json:"id"`
ProjectId int `json:"project_id"`
Url string `json:"url"`
Type string `json:"type"`
}
func AddProjectPics(data []string, project_pic_type string, project_id int) bool {
sql := "INSERT INTO `project_pics` (`project_id`,`url`,`type`) VALUES "
// 循環(huán)data數(shù)組,組合sql語句
for key, value := range data {
if len(data)-1 == key {
//最后一條數(shù)據(jù) 以分號結(jié)尾
sql += fmt.Sprintf("(%d,'%s','%s');", project_id, value, project_pic_type)
} else {
sql += fmt.Sprintf("(%d,'%s','%s'),", project_id, value, project_pic_type)
}
}
db.Exec(sql)
return true
}
效果

image.png