// Define Database Connection db, err := gorm.Open("mysql", "user:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local") // Check Error if err != nil { panic("failed to connect database") } // Close the DB Connection after execution completes defer db.Close()
// Define Model Struct type User struct { gorm.Model FirstName string LastName string Email string `gorm:"uniqueIndex"` } // Create Table with Model db.CreateTable(&User{})
// Get a Single Record var user User db.First(&user, 1) // find user with integer primary key 1 // Get a Single Record with Condition db.Where("email = ?", "[email protected]").First(&user) // Get Multiple Records with Condition var users []User db.Where("age > ?", 20).Find(&users)In conclusion, the `github.com.jinzhu.gorm` package is a Go library that provides a number of useful features for managing relational databases. It is a powerful and flexible library that is well-suited for any project that involves working with databases.