Home >Backend Development >Golang >golang paging query statement
There are many ways to implement paging queries in Go language. This article will introduce one of the ways to implement it: using the limit and offset keywords. The specific implementation is as follows:
func queryData(pageSize, pageNum int) ([]Data, error) { // 计算数据偏移量 offset := (pageNum - 1) * pageSize // 拼接查询语句 query := fmt.Sprintf("SELECT * FROM data LIMIT %d OFFSET %d", pageSize, offset) // 执行查询语句并返回结果 rows, err := db.Query(query) if err != nil { return nil, err } defer rows.Close() data := []Data{} for rows.Next() { // 解析查询结果 var id int var name string var age int err = rows.Scan(&id, &name, &age) if err != nil { return nil, err } // 将数据添加到结果集中 data = append(data, Data{ ID: id, Name: name, Age: age, }) } return data, nil }
This function can accept two parameters: pageSize and pageNum, which represent the data size of each page and the current page number respectively. The function internally uses these two parameters to calculate the offset of the data, uses the limit and offset keywords to splice the query statement, then executes the query statement and parses the result set, and finally adds the data to the result set and returns it.
Using this function to perform paging query is very simple. You only need to specify the data size of each page and the current page number. For example, we can perform paging query based on 10 pieces of data per page. The code to query the data on page 3 is as follows:
data, err := queryData(10, 3) if err != nil { log.Fatal(err) } // 输出查询结果 for _, d := range data { fmt.Printf("ID=%d, Name=%s, Age=%d ", d.ID, d.Name, d.Age) }
This code will query the data on page 3. The data size of each page is 10 pieces, and the query will The results are output to the console. If an error occurs during the query, the program will print the error message and exit.
The above is the detailed content of golang paging query statement. For more information, please follow other related articles on the PHP Chinese website!