在使用Gorm和SQLite时,创建记录后必须保存它才能将其保存到数据库中吗?

huangapple go评论78阅读模式
英文:

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: { ... }

huangapple
  • 本文由 发表于 2021年10月22日 17:06:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/69674225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定