golang学习笔记: 使用gorm操作mysql增删改查
一、连接mysql
1 import ( 2 "github.com/jinzhu/gorm" 3 _ "github.com/jinzhu/gorm/dialects/mysql" 4 ) 5 6 func main() { 7 db, err := gorm.Open("mysql", "user:password@(localhost)/dbname?charset=utf8&parseTime=True&loc=Local") 8 defer db.Close() 9 }
二、定义model
1 type User struct { 2 gorm.Model 3 Name string 4 Age sql.NullInt64 5 Birthday *time.Time 6 Email string `gorm:"type:varchar(100);unique_index"` 7 Role string `gorm:"size:255"` // set field size to 255 8 MemberNumber *string `gorm:"unique;not null"` // set member number to unique and not null 9 Num int `gorm:"AUTO_INCREMENT"` // set num to auto incrementable 10 Address string `gorm:"index:addr"` // create index with name `addr` for address 11 IgnoreMe int `gorm:"-"` // ignore this field 12 }
三、创建user
1 user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()} 2 3 db.NewRecord(user) // => returns `true` as primary key is blank 4 5 db.Create(&user)
四、获取user
// Get first record, order by primary key db.First(&user) //// SELECT * FROM users ORDER BY id LIMIT 1; // Get one record, no specified order db.Take(&user) //// SELECT * FROM users LIMIT 1; // Get last record, order by primary key db.Last(&user) //// SELECT * FROM users ORDER BY id DESC LIMIT 1; // Get all records db.Find(&users) //// SELECT * FROM users; // Get record with primary key (only works for integer primary key) db.First(&user, 10) //// SELECT * FROM users WHERE id = 10;
// Get first matched record db.Where("name = ?", "jinzhu").First(&user) //// SELECT * FROM users WHERE name = 'jinzhu' ORDER BY id LIMIT 1; // Get all matched records db.Where("name = ?", "jinzhu").Find(&users) //// SELECT * FROM users WHERE name = 'jinzhu'; // <> db.Where("name <> ?", "jinzhu").Find(&users) //// SELECT * FROM users WHERE name <> 'jinzhu'; // IN db.Where("name IN (?)", []string{"jinzhu", "jinzhu 2"}).Find(&users) //// SELECT * FROM users WHERE name in ('jinzhu','jinzhu 2'); // LIKE db.Where("name LIKE ?", "%jin%").Find(&users) //// SELECT * FROM users WHERE name LIKE '%jin%'; // AND db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users) //// SELECT * FROM users WHERE name = 'jinzhu' AND age >= 22; // Time db.Where("updated_at > ?", lastWeek).Find(&users) //// SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00'; // BETWEEN db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
// Struct db.Where(&User{Name: "jinzhu", Age: 20}).First(&user) //// SELECT * FROM users WHERE name = "jinzhu" AND age = 20 ORDER BY id LIMIT 1; // Map db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users) //// SELECT * FROM users WHERE name = "jinzhu" AND age = 20; // Slice of primary keys db.Where([]int64{20, 21, 22}).Find(&users) //// SELECT * FROM users WHERE id IN (20, 21, 22);
db.Not("name", "jinzhu").First(&user) //// SELECT * FROM users WHERE name <> "jinzhu" ORDER BY id LIMIT 1; // Not In db.Not("name", []string{"jinzhu", "jinzhu 2"}).Find(&users) //// SELECT * FROM users WHERE name NOT IN ("jinzhu", "jinzhu 2"); // Not In slice of primary keys db.Not([]int64{1,2,3}).First(&user) //// SELECT * FROM users WHERE id NOT IN (1,2,3) ORDER BY id LIMIT 1; db.Not([]int64{}).First(&user) //// SELECT * FROM users ORDER BY id LIMIT 1; // Plain SQL db.Not("name = ?", "jinzhu").First(&user) //// SELECT * FROM users WHERE NOT(name = "jinzhu") ORDER BY id LIMIT 1; // Struct db.Not(User{Name: "jinzhu"}).First(&user) //// SELECT * FROM users WHERE name <> "jinzhu" ORDER BY id LIMIT 1;
db.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&users) //// SELECT * FROM users WHERE role = 'admin' OR role = 'super_admin'; // Struct db.Where("name = 'jinzhu'").Or(User{Name: "jinzhu 2"}).Find(&users) //// SELECT * FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'; // Map db.Where("name = 'jinzhu'").Or(map[string]interface{}{"name": "jinzhu 2"}).Find(&users) //// SELECT * FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2';
// Get by primary key (only works for integer primary key) db.First(&user, 23) //// SELECT * FROM users WHERE id = 23; // Get by primary key if it were a non-integer type db.First(&user, "id = ?", "string_primary_key") //// SELECT * FROM users WHERE id = 'string_primary_key'; // Plain SQL db.Find(&user, "name = ?", "jinzhu") //// SELECT * FROM users WHERE name = "jinzhu"; db.Find(&users, "name <> ? AND age > ?", "jinzhu", 20) //// SELECT * FROM users WHERE name <> "jinzhu" AND age > 20; // Struct db.Find(&users, User{Age: 20}) //// SELECT * FROM users WHERE age = 20; // Map db.Find(&users, map[string]interface{}{"age": 20}) //// SELECT * FROM users WHERE age = 20;
五、更新user
db.First(&user) user.Name = "jinzhu 2" user.Age = 100 db.Save(&user)
// Update single attribute if it is changed db.Model(&user).Update("name", "hello") //// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111; // Update single attribute with combined conditions db.Model(&user).Where("active = ?", true).Update("name", "hello") //// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111 AND active=true; // Update multiple attributes with `map`, will only update those changed fields db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false}) //// UPDATE users SET name='hello', age=18, actived=false, updated_at='2013-11-17 21:34:10' WHERE id=111; // Update multiple attributes with `struct`, will only update those changed & non blank fields db.Model(&user).Updates(User{Name: "hello", Age: 18}) //// UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 21:34:10' WHERE id = 111; // WARNING when update with struct, GORM will only update those fields that with non blank value // For below Update, nothing will be updated as "", 0, false are blank values of their types db.Model(&user).Updates(User{Name: "", Age: 0, Actived: false})
db.Model(&user).Select("name").Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false}) //// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111; db.Model(&user).Omit("name").Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false}) //// UPDATE users SET age=18, actived=false, updated_at='2013-11-17 21:34:10' WHERE id=111;
六、删除user
// Delete an existing record db.Delete(&email) //// DELETE from emails where id=10; // Add extra SQL option for deleting SQL db.Set("gorm:delete_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Delete(&email) //// DELETE from emails where id=10 OPTION (OPTIMIZE FOR UNKNOWN);
db.Where("email LIKE ?", "%jinzhu%").Delete(Email{}) //// DELETE from emails where email LIKE "%jinzhu%"; db.Delete(Email{}, "email LIKE ?", "%jinzhu%") //// DELETE from emails where email LIKE "%jinzhu%";
posted on 2020-08-22 20:05 limanxian 阅读(1590) 评论(0) 编辑 收藏 举报