download:
//csv
func doDown() {
csvName := downDir + time.Now().Format("2006-01-02") + ".csv"
file, _ := os.OpenFile(csvName, os.O_WRONLY|os.O_CREATE, os.ModePerm)
w := csv.NewWriter(file)
//
file.WriteString("\xEF\xBB\xBF")
w.Write([]string{"", "", ""})
pageSize := 1000
page := 1
db, err := mysqlUtil.CreateReadDb()
if err != nil {
fmt.Println("connect db err")
os.Exit(1)
}
for {
offset := (page - 1) * pageSize
sqlStr := `select title,uptime,url from film order by uptime desc limit ` + strconv.Itoa(offset) + `,` + strconv.Itoa(pageSize)
fmt.Println(sqlStr)
res, err := db.Query(sqlStr)
if err != nil {
fmt.Println("query err ", err)
}
rows, err := mysqlUtil.GetRows(res)
if len(rows) > 0 {
for _, v := range rows {
w.Write([]string{v["title"], v["uptime"], host + v["url"]})
}
} else {
break
}
pagePP
}
w.Flush()
}
sql is data taken in reverse order according to uptime. Why is the order out of order when writing csv?
prints the output and finds that it is the problem with rows, err: = mysqlUtil.GetRows (res).
the code for this function is posted here:
func GetRows(query *sql.Rows) (map[int]map[string]string, error) {
column, err := query.Columns() //
if err != nil {
return nil, fmt.Errorf("getRows db err:", err)
}
values := make([][]byte, len(column)) //valuesbyte
scans := make([]interface{}, len(column)) //len(column)
for i := range values { //[][]byte
scans[i] = &values[i]
}
results := make(map[int]map[string]string) //map
i := 0
for query.Next() { //
if err := query.Scan(scans...); err != nil { //query.Scanscans[i] = &values[i],values
return nil,fmt.Errorf("scan result db err:", err)
}
row := make(map[string]string) //
for k, v := range values { //valuesrow
key := column[k]
row[key] = string(v)
}
results[i] = row //
iPP
}
return results,nil
}
because the map,map returned is unordered, all return types need to be adjusted as follows:
func GetRowsSlice(query *sql.Rows) ([]map[string]string, error) {
column, err := query.Columns() //
if err != nil {
return nil, fmt.Errorf("getRows db err:", err)
}
values := make([][]byte, len(column)) //valuesbyte
scans := make([]interface{}, len(column)) //len(column)
for i := range values { //[][]byte
scans[i] = &values[i]
}
results := []map[string]string{} //map
i := 0
for query.Next() { //
if err := query.Scan(scans...); err != nil { //query.Scanscans[i] = &values[i],values
return nil,fmt.Errorf("scan result db err:", err)
}
row := make(map[string]string) //
for k, v := range values { //valuesrow
key := column[k]
row[key] = string(v)
}
//results[i] = row //
results = append(results, row)
iPP
}
return results,nil
}