英文:
Must I save a record after creating it to save it in SQLITE with Gorm?
问题
我正在使用Gorm和SQLITE数据库,需要保存一条新记录。
我遇到的问题是,当我创建一条记录并重新启动程序时,数据库中找不到该记录。在创建记录后是否需要保存记录?
Gorm文档中给出的示例程序没有保存记录。
英文:
I’m using a SQLITE database with Gorm and need to save a new record.
The problem I have is that when I create a record and restart the program, the record is not found in the database. Is saving the record required after creating it ?
The example program given in the Gorm documentation doesn’t save the record.
答案1
得分: 1
您不需要对已经传递给Create
的记录进行Save
操作。
您可以通过运行以下代码进行测试:
main.go
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&Product{})
var product Product
if db.First(&product).Error == gorm.ErrRecordNotFound {
fmt.Println("no product record, creating now...")
db.Create(&Product{Code: "D42", Price: 100})
} else {
fmt.Printf("product record found: %v", product)
}
}
go run main.go
no product record, creating now...
go run main.go
product record found: { ... }
英文:
You don't have to Save
a record that you've passed to Create
already.
You can test this by running the following:
main.go
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&Product{})
var product Product
if db.First(&product).Error == gorm.ErrRecordNotFound {
fmt.Println("no product record, creating now...")
db.Create(&Product{Code: "D42", Price: 100})
} else {
fmt.Printf("product record found: %v", product)
}
}
go run main.go
no product record, creating now...
go run main.go
product record found: { ... }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论