1、安装gorm
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
2、引入
import (
"gorm.io/gorm"
"gorm.io/driver/sqlite"
)
3、连接(使用原生)
func main() {
dsn := "root:root678@tcp(127.0.0.1:3306)/topics?charset=utf8mb4&parseTime=True&loc=Local"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
rows,_ := db.Raw("select topic_id,topic_title from topics").Rows()
for rows.Next(){
var t_id int
var t_title string
rows.Scan(&t_id, &t_title)
fmt.Println(t_id, t_title)
}
}
3、连接(使用ORM)
func main() {
dsn := "root:root678@tcp(127.0.0.1:3306)/topics?charset=utf8mb4&parseTime=True&loc=Local"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
var tcs []src.TopicClass
db.Table("topic666").Where("class_name=?","技术类").Find(&tcs)
fmt.Println(tcs)
}
type TopicClass struct{
ClassId int
ClassName string
ClassRemark string
}