import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) db, err := gorm.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database_name?charset=utf8&parseTime=True") if err != nil { panic("failed to connect database") } defer db.Close()
type User struct { gorm.Model Name string Age int } func main() { db, err := gorm.Open(...) if err != nil { panic("failed to connect database") } defer db.Close() // AutoMigrate db.AutoMigrate(&User{}) // Create db.Create(&User{Name: "John", Age: 32}) }
var users []User // Find all users db.Find(&users) // Find user with given ID db.First(&User{}, 1) // Find users with given conditions db.Where("age > ?", 18).Find(&users) // Order by age db.Order("age desc").Find(&users)These are some examples of querying data using the package. In conclusion, the github.com/jinzhu/gorm package is a powerful ORM library that allows developers to interact with various databases using idiomatic Go syntax. The package supports a wide range of databases including MySQL, PostgreSQL, SQLite, and SQL Server.