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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格