duanbei1903 2017-06-13 14:11
浏览 137
已采纳

使用go从我的sqlite数据库获取最新记录

I want to query my sqlite db to get the last id in my book table then insert the data with the last id + 1. I am new to Go and I can't figure out how to set my lastid int variable. Any help would be greatly appreciated.

func getBookLastID() {

  var lastid int
  err := db.QueryRow("select max(id) from books").Scan(&lastid)
  fmt.Println(lastid)
  return (lastid + 1)
}

func insertBook(name, author string, pages int, publicationDate time.Time) (int, error) {
        //Create
        var bookID int

        var lastid int 
        lastid = getBookLastID()

        err := db.QueryRow(`INSERT INTO books(id, name, author, pages, publication_date) VALUES($1, $2, $3, $4, $5)`, lastid, name, author, pages, publicationDate).Scan(&bookID)

        if err != nil {
                return 0, err
        }

        fmt.Printf("Last inserted ID: %v
", bookID)
        return bookID, err
}
  • 写回答

1条回答 默认 最新

  • douquan1953 2017-06-13 15:03
    关注

    I was missing "int" in the func

    Wrong:

    func getBookLastID() {....
    

    Correct:

    func getBookLastID() int {....
    

    Correct All:

    func getBookLastID() int { 
    
        var id int
    
        err := db.QueryRow("select ifnull(max(id), 0) as id from books").Scan(&id)
        if err != nil {
          panic(err)
        }
        fmt.Println("New record ID is:", id + 1)
        return id + 1
    }
    
    func insertBook(name, author string, pages int, publicationDate time.Time) (int, error) {
        //Create
    
        lastid := getBookLastID() 
    
    
        res, err := db.Exec(`INSERT INTO books(id, name, author, pages, publication_date) VALUES($1, $2, $3, $4, $5)`, lastid, name, author, pages, publicationDate)
    
        if err != nil {
            return 0, err
        }
    
        rowsCreated, err := res.RowsAffected()
    
            if err != nil {
            return 0, err
        }
    
        return int(rowsCreated), err
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!