插入测试数据
package mainimport ("fmt""gorm.io/driver/mysql""gorm.io/gorm"
)type Student struct {ID int64Name string `gorm:"size:6"`Age intEmail *string
}func (*Student) TableName() string {return "student"
}func main() {dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})db.AutoMigrate(&Student{})var sList []Studentcount := db.Find(&sList).Delete(&sList).RowsAffectedfmt.Println("count=", count)email1 := "12396836709@qq.com"sList = []Student{{ID: 1,Name: "lucas",Age: 30,Email: &email1,},{ID: 2,Name: "yanzi",Age: 28,Email: &email1,},{ID: 3,Name: "lulei",Age: 29,Email: &email1,},{ID: 4,Name: "jerry",Age: 25,Email: &email1,},}db.Create(&sList)}
Where语句里面条件 where + find = select * from table where...........
其实就是sql语句当中的where
var sList []Studentdb.Debug().Where("name = ?", "lucas").Find(&sList)fmt.Println(sList)[0.746ms] [rows:1] SELECT * FROM `student` WHERE name = 'lucas'
[{1 lucas 30 0xc0001c91f0}]
之前学的这种写法也是可以的
var s Studentdb.Debug().Find(&s, "name = ?", "lucas")fmt.Println(s)[1.552ms] [rows:1] SELECT * FROM `student` WHERE name = 'lucas'
{1 lucas 30 0xc0001c9300}
使用结构体查询
如果是零值,那么查询的时候就不会将零值作为查询带上了
s = Student{Name: "lucas",Age: 30,}db.Debug().Where(&s).Find(&s)[1.543ms] [rows:1] SELECT * FROM `student` WHERE `student`.`name` = 'lucas' AND `student`.`age` = 30