I went through the documentation to insert multiple records into postgres using the package pg https://pkg.go.dev/github.com/go-pg/pg/v10#example-DB.Model-BulkInsert .
db := modelDB()
book1 := &Book{
Title: "new book 1",
}
book2 := &Book{
Title: "new book 2",
}
_, err := db.Model(book1, book2).Insert()
if err != nil {
panic(err)
}
fmt.Println(book1, book2)
Honestly i dont like this solution since it does not allow me to pass an array of books. Cause the use case i have is that i wont know the number of books i need to insert.
Should i be using transactions here cause i might have to insert more than 20 record at once. If yes, please help as am not finding good examples for this one.
PS: Must use pg library.
just put your book, in array of slices, and insert it, go-pg support insert batch
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.