gpt4 book ai didi

go - 使用 go 从我的 sqlite 数据库中获取最后一条记录

转载 作者:数据小太阳 更新时间:2023-10-29 03:24:58 24 4
gpt4 key购买 nike

我想查询我的 sqlite 数据库以获取我的书表中的最后一个 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
}

最佳答案

我在函数中缺少“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

}

关于go - 使用 go 从我的 sqlite 数据库中获取最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44524001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com