连接数据库
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main() {
db, err := gorm.Open(
"mysql",
"root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local",
)
if err != nil {
panic(err)
}
defer db.Close()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
}
创建表
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
db, err := gorm.Open(
"mysql",
"root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local",
)
if err != nil {
panic(err)
}
defer db.Close()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
db.AutoMigrate(&User{})
}
新增数据
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
db, err := gorm.Open(
"mysql",
"root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local",
)
if err != nil {
panic(err)
}
defer db.Close()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
u1 := &User{1, "张三", 23}
db.Create(u1)
}
查找数据
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
db, err := gorm.Open(
"mysql",
"root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local",
)
if err != nil {
panic(err)
}
defer db.Close()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
var uu User
db.Find(&uu, "name=?", "张三")
fmt.Printf("%#v\n", uu)
}
修改数据
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
db, err := gorm.Open(
"mysql",
"root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local",
)
if err != nil {
panic(err)
}
defer db.Close()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
var user = User{Id: 1}
db.Model(&user).Update("name", "李四")
fmt.Printf("%#v\n", user)
var uu User
db.Find(&uu, "id=?", 1)
fmt.Printf("%#v\n", uu)
}
删除数据
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
db, err := gorm.Open(
"mysql",
"root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local",
)
if err != nil {
panic(err)
}
defer db.Close()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
var user = User{Id: 1}
db.Delete(&user)
fmt.Printf("%#v\n", user)
var uu User
db.Find(&uu, "id=?", 1)
fmt.Printf("%#v\n", uu)
}
领取专属 10元无门槛券
私享最新 技术干货