GO语言分组批量插入数据算法

database

package main

import "fmt"

// Point 点名

type Point struct {

PointID uint64 `json:"pointID"`

PathName string `json:"pathName"`

PointValue float32 `json:"pointValue"`

StoreTime string `json:"storeTime"`

}

func getSqlList(pointList []Point, groupSize int) []string {

const insertHeader string = "INSERT INTO `local_data`(`point_id`,`path_name`,`point_value`,`store_time`) VALUES"

sqlList := []string{}

sql := ""

for i := 0; i < len(pointList); i++ {

if i%groupSize == 0 {

if sql != "" {

//把上次拼接的SQL结果存储起来

sqlList = append(sqlList, sql)

}

//重置SQL

sql = insertHeader

}

if sql != insertHeader {

sql = sql + ","

}

sql = sql + fmt.Sprintf("(%d,"%s",%f,"%s")",

pointList[i].PointID,

pointList[i].PathName,

pointList[i].PointValue,

pointList[i].StoreTime)

}

//把最后一次生成的SQL存储起来

sqlList = append(sqlList, sql)

return sqlList

}

func main() {

points := []Point{

Point{1, "p1", 3.14, "2013-11-10 12:00:00"},

Point{2, "p1", 3.14, "2013-11-10 12"},

Point{3, "p1", 3.14, "2013-11-10 12"},

Point{4, "p1", 3.14, "2013-11-10 12"},

Point{5, "p1", 3.14, "2013-11-10 12"},

Point{6, "p1", 3.14, "2013-11-10 12"},

Point{7, "p1", 3.14, "2013-11-10 12"},

Point{8, "p1", 3.14, "2013-11-10 12"},

Point{9, "p1", 3.14, "2013-11-10 12"},

Point{10, "p1", 3.14, "2013-11-10 12"},

Point{11, "p1", 3.14, "2013-11-10 12"},

Point{12, "p1", 3.14, "2013-11-10 12"},

Point{13, "p1", 3.14, "2013-11-10 12"},

Point{14, "p1", 3.14, "2013-11-10 12"},

Point{15, "p1", 3.14, "2013-11-10 12"},

Point{16, "p1", 3.14, "2013-11-10 12"},

Point{17, "p1", 3.14, "2013-11-10 12"},

}

sqls := getSqlList(points, 5)

for _, s := range sqls {

fmt.Println(s)

}

}

 

以上是 GO语言分组批量插入数据算法 的全部内容, 来源链接: utcz.com/z/531484.html

回到顶部