英文:
Golang sqldatabase rows.Next
问题
rows.Next()方法会逐行遍历查询结果集。当调用rows.Next()时,它会将游标移动到下一行,并返回一个布尔值,指示是否还有更多的行可供遍历。如果在循环中再次调用rows.Next(),它会继续将游标移动到下一行,直到遍历完所有的行。
在你的代码中,当你在if !rows.Next()
之后立即调用for rows.Next()
时,由于在if
语句中已经调用了一次rows.Next()
,游标已经移动到了下一行,所以for
循环中的代码块不会被执行。
如果你想在if
语句中判断是否有数据行,并在之后的循环中遍历数据行,你可以将if
语句和for
循环分开处理,如下所示:
rows, err := db.Query(query)
if err != nil {
Error.Printf("error querying: %v", err)
}
if !rows.Next() {
// insert new data
} else {
for rows.Next() {
fmt.Println("-----")
// do update
}
}
这样,如果没有数据行,将执行插入新数据的逻辑;如果有数据行,将进入循环并执行更新的逻辑。
英文:
Does rows.Next go to the end of the list and not let you go back to the beginning? I want to run a query that checks if there is data for a specific object in a database. If there is that object, I want to update it. If it's not there, i want to insert a new row.
So I do this:
rows, err := db.Query(query)
if err != nil {
Error.Printf("error querying: %v", err)
}
if !rows.Next() {
// insert new data
}
that works on it's own like I expect. But if I do this instead and at more logic to the end of the snippet:
rows, err := db.Query(query)
if err != nil {
Error.Printf("error querying: %v", err)
}
if !rows.Next() {
// insert new data
}
for rows.Next() {
fmt.Println("-----")
// do update
}
My for rows.Next() never gets entered. If I move the for rows.Next()
block above the if !rows.Next()
block, it does work as expected. So is there something that happens when you call Next() that you have to do to read from the query again?
答案1
得分: 0
你可能想要这样的代码:
rows, err := db.Query(query)
if err != nil {
Error.Printf("查询错误:%v", err)
}
shouldinsert := true
for rows.Next() {
shouldinsert = false
fmt.Println("-----")
// 进行更新操作
}
if shouldinsert {
// 插入新数据
}
英文:
You probably want something like this:
rows, err := db.Query(query)
if err != nil {
Error.Printf("error querying: %v", err)
}
shouldinsert := true
for rows.Next() {
shouldinsert = false
fmt.Println("-----")
// do update
}
if shouldinsert {
// insert new data
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论