douyan8070 2017-01-09 20:24
浏览 32
已采纳

golang sqldatabase行。

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? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dousidan1279 2017-01-09 22:49
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?