Home > Software design >  Must I save a record after creating it to save it in SQLITE with Gorm?
Must I save a record after creating it to save it in SQLITE with Gorm?

Time:10-23

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.

CodePudding user response:

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