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

报告相同问题?

悬赏问题

  • ¥15 微信夜间被转走了1w对,当天手机剪切板里就出现了这个乱码,有铁子可以看看是啥吗可以
  • ¥50 跑通github上的代码 深度学习 pytorch
  • ¥50 求写,批处理调用分区助手分区脚本
  • ¥15 求购HI3519AV100开发板
  • ¥15 请问1553 RT怎么测试,没有BC有方法吗
  • ¥100 业务编程如何选择学习方向和内容?
  • ¥15 wamp3.3.5安装完成后图标正常显示绿色,鼠标左右键点击图标均无反应。求解决方法。
  • ¥15 鼠标点击的这条记录了什么?
  • ¥15 在写pid调速的程序时,电机始终维持最大速度
  • ¥15 【有偿】调用DXGI截图初始化失败,提示0xf 887a0004