大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说GO语言分组批量插入数据算法,希望您对编程的造诣更进一步.
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)
}
}
代码100分
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/10842.html