Golang sqldatabase rows.Next 的中文翻译是:Golang sqldatabase 的 rows.Next 方法。

huangapple go评论72阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2017年1月10日 04:24:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/41556320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定