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

使用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
    
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题