GORM is an ORM framework for the Go programming language, whose full name is "Go Object Relational Mapping". It is a powerful ORM that is easy to use and efficient. Below we will introduce in detail how to learn and use GORM.
Installing GORM
Before you start using GORM, you need to download and install it. The installation process is simple. You can use the following command to install GORM:
go get -u github.com/jinzhu/gorm
Connect to the database
When using GORM, you need to set the database connection information in the configuration file. Here is an example of connecting to a MySQL database:
import ( "github.com/jinzhu/gorm" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := gorm.Open("mysql", "{username}:{password}@tcp({host}:{port})/{database}?charset=utf8&parseTime=True&loc=Local") if err != nil { panic(err) } defer db.Close() }
In order to perform database operations, you need to pass it to GORM. The following is sample code for passing a database example to GORM:
db, err := gorm.Open("mysql", "{username}:{password}@tcp({host}:{port})/{database}?charset=utf8&parseTime=True&loc=Local") if err != nil { panic(err) } defer db.Close() type User struct { ID uint `gorm:"primary_key"` Name string `gorm:"size:255"` } // 创建表 db.CreateTable(&User{})
query
db.First(&user, 1) // SELECT * FROM users WHERE id = 1; db.Find(&users) // SELECT * FROM users; db.Where("name = ?", "jinzhu").Find(&users) // SELECT * FROM users WHERE name = 'jinzhu';
insert
db.Create(&User{Name: "jinzhu"}) // INSERT INTO users (name) VALUES ("jinzhu");
update
db.Model(&user).Update("name", "jinzhu") // UPDATE users SET name = "jinzhu" WHERE id = 1;
Delete
db.Delete(&user) // DELETE FROM users WHERE id = 1;
The above is the detailed content of How to learn and use Go's ORM framework GORM. For more information, please follow other related articles on the PHP Chinese website!