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

时间:2017-06-13 14:11:00

标签: go

我想查询我的sqlite数据库以获取我的book表中的最后一个id,然后插入最后一个id + 1的数据。我是Go的新手,我无法弄清楚如何设置我的lastid int变量。任何帮助将不胜感激。

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\n", bookID)
        return bookID, err
}

1 个答案:

答案 0 :(得分:0)

我失踪了" int"在功能

错误:

func getBookLastID() {....

正确:

func getBookLastID() int {....

纠正所有:

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

}