我有一个小问题。我在对数据库进行查询后尝试迭代rows
,但是我无法再次遍历它以找到females
。
我相信这是因为在迭代rows
打印出来之后,指针留在最后并且无法返回。
rows2, rowErr :=db.Query("SELECT GIVENNAME,gender, count(givenname) as Frequency from people group by givenname order by givenname asc")
for rows2.Next() {
nextErr := rows2.Scan(&givenName,&gender, &frequency)
if nextErr != nil{
log.Fatal(nextErr.Error())
}
if gender == "male" {
fmt.Println(givenName, gender, frequency)
}
}
fmt.Println("")
for rows2.Next() {
nextErr := rows2.Scan(&givenName,&gender, &frequency)
if nextErr != nil{
log.Fatal(nextErr.Error())
}
if gender == "female" {
fmt.Println(givenName, gender, frequency)
}
}
反正我可以把指针放在开头吗?或者我还需要做另一个查询吗?
答案 0 :(得分:2)
您无法“回滚”指向前一个值的指针,因此您必须使用另一个(临时)var来进行迭代。
rows2, rowErr := db.Query("SELECT GIVENNAME, gender, count(givenname) as Frequency from people group by givenname order by givenname asc")
var list1, list2 MyPeopleStruct
temp := rows2
for temp.Next() {
nextErr := rows2.Scan(&givenName,&gender, &frequency)
if nextErr != nil{
log.Fatal(nextErr.Error())
}
if gender == "male" {
fmt.Println(givenName, gender, frequency)
}
}
fmt.Println("")
temp = rows2 // reinitialise it to the actual value you need
for temp.Next() {
nextErr := rows2.Scan(&givenName,&gender, &frequency)
if nextErr != nil{
log.Fatal(nextErr.Error())
}
if gender == "female" {
fmt.Println(givenName, gender, frequency)
}
}
无论如何,为什么你甚至需要制作两个不同的for loop
s?
你不能只使用一个吗?像:
type MyPeopleStruct struct{
Gender string
Name string
Frequency int
}
rows2, rowErr := db.Query("SELECT GIVENNAME, gender, count(givenname) as Frequency from people group by givenname order by givenname asc")
var listM, listF []MyPeopleStruct
temp := rows2
for temp.Next() {
nextErr := rows2.Scan(&givenName,&gender, &frequency)
if nextErr != nil{
log.Fatal(nextErr.Error())
}
if gender == "male" {
fmt.Println(givenName, gender, frequency)
listM = append(listM, MyPeopleStruct{gender,givenName,frequency})
}
if gender == "female" {
fmt.Println(givenName, gender, frequency)
listF = append(listF, MyPeopleStruct{gender,givenName,frequency})
}
}
// Use listM and listF