Created
January 27, 2019 07:26
-
-
Save jarifibrahim/72c7b24f8ba08baa1a2266c302a8c625 to your computer and use it in GitHub Desktop.
GORM - Insert, Update and Delete operation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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