Skip to content

Instantly share code, notes, and snippets.

@jarifibrahim
Created January 27, 2019 07:26
Show Gist options
  • Save jarifibrahim/72c7b24f8ba08baa1a2266c302a8c625 to your computer and use it in GitHub Desktop.
Save jarifibrahim/72c7b24f8ba08baa1a2266c302a8c625 to your computer and use it in GitHub Desktop.
GORM - Insert, Update and Delete operation
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "L1212", Price: 1000})
// Read
var product Product
db.First(&product, 1) // find product with id 1
db.First(&product, "code = ?", "L1212") // find product with code l1212
// Update - update product's price to 2000
db.Model(&product).Update("Price", 2000)
// Delete - delete product
db.Delete(&product)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment