ORM(Object-Relational Mapping)是一种编程技术,用于将面向对象编程语言中的对象模型和关系数据库中的数据模型相互映射。ORM框架可以把数据操作从 SQL 语句中抽离出来,将关系型数据库中的表映射成对象,通过面向对象的方式操作数据库,提高了开发效率和代码可读性。ORM框架通常会提供持久化(Persistence)、查询数据(Query)和关系映射(Relationship Mapping)等核心功能。使用ORM,开发者可以更加专注于业务逻辑的实现,无需过多关注底层数据操作细节。常用的ORM框架有Hibernate、MyBatis、Entity Framework、Django ORM等。
package main
import "github.com/jinzhu/gorm"
func main() {
db, err := gorm.Open("mysql", "root:password@(127.0.0.1:3306)/db1?"+"charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer db.Close()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
}
CREATE TABLE `gorm_users`(
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`phone` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
)ENGINE = InnoDB AUTO_INCREMENT = 39 DEFAULT CHARSET = utf8
type GormUser struct {
ID uint `json:"id"`
Phone string `json:"phone"`
Name string `json:"name"`
Password string `json:"password"`
}
import (
"github.com/jinzhu/gorm"
"crypto/md5"
"encoding/hex"
)
func insert(db *gorm.DB) {
GormUser := GormUser{
Phone: "1888888888",
Name: "Shirdon",
Password: md5Password("666666"),
}
db.Save(&GormUser)
//db.Create(&GormUser)
}
func md5Password(password string) string {
hasher := md5.New()
hasher.Write([]byte(password))
return hex.EncodeToString(hasher.Sum(nil))
}
func delete(db *gorm.DB) {
var GormUser = new(GormUser)
db.Where("phone = ?","1388888888").Delete(&GormUser)
}
func selectDb(db *gorm.DB) {
var GormUser = new(GormUser)
db.Where("phone = ?","1888888888").Find(&GormUser)
//db.First(&GormUser,"phone=?","1888888888")
fmt.Println(GormUser)
}
func update(db *gorm.DB) {
var GormUser = new(GormUser)
db.Model(&GormUser).Where("phone = ?","1888888888").Update("phone","1388888888")
}
func update(db *gorm.DB) {
var GormUser = new(GormUser)
err := db.Model(&GormUser).Where("phone = ?","1888888888").Update("phone","1388888888").Error
if err != nil {
//...
}
}
func transc(db *gorm.DB) {
tx := db.Begin()
GormUser := GormUser{
Phone: "18888888888",
Name: "Shirdon",
Password: md5Password("666666"),
}
if err := tx.Create(&GormUser).Error;err!=nil {
tx.Rollback()
fmt.Println(err)
}
db.First(&GormUser,"phone =?","18888888888")
tx.Commit()
}
db.LogMode(true)
db.SetLogger(log.New(os.Stdout,"\r\n",0))
maxIdle := 30
maxConn := 30
orm.RegisterDataBase("default","mysql","root:root@/orm_test?charset=utf8",maxIdle,maxConn)
//orm.SetMaxIdleConns("default",30)
//orm.SetMaxOpenConns("default",30)
func init() {
orm.RegisterModel(new(BeegoUser))
//orm.RegisterModel(new(BeegoUser),new(Profile),new(Post))
//orm.RegisterModel("prefix",new(BeegoUser))
}
CREATE TABLE `beego_user`(
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增 ID',
`name` varchar(20) DEFAULT '' COMMENT '名字',
`phone` varchar(20) DEFAULT '' COMMENT '电话',
PRIMARY KEY(`id`)
)ENGINE = InnoDB DEFAULT CHARSET=utf8
type BeegoUser struct {
Id int
Name string
Phone string
}
package main
import (
"fmt"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
type BeegoUser struct {
Id int
Name string
Phone string
}
func main() {
o := orm.NewOrm()
user := new(BeegoUser)
user.Name = "Shirdon"
user.Phone = "18888888888"
fmt.Println(o.Insert(user))
}
func delete() {
o := orm.NewOrm()
user:= BeegoUser{}
user.Id=7
if num , err := o.Delete(&user);err!=nil{
fmt.Println("删除失败")
} else {
fmt.Println("删除数据影响的行数:",num)
}
}
func selectDb() {
o := orm.NewOrm()
user := BeegoUser{} // 根据条件查询记录
user.Id = 6
err := o.Read(&user)
if err == orm.ErrNoRows {
fmt.Println("记录不存在")
} else if err == orm.ErrMissPK {
fmt.Println("缺少主键")
} else if err != nil {
fmt.Println(err)
} else {
fmt.Println(user)
}
}
func update() {
o := orm.NewOrm()
user := BeegoUser{} // 根据条件查询记录
user.Id=6
user.Name="James"
num, err := o.Update(&user)
if err != nil {
fmt.Println("更新失败")
} else {
fmt.Println("更新影响的行数:",num)
}
}
func rowQueryDb() {
o := orm.NewOrm()
var r orm.RawSeter
r = o.Raw("UPDATE user SET name =? WHERE name =?", "James","jim")
}
func transc() {
o := orm.NewOrm()
o.Begin() // 开启事务
user1 := BeegoUser{}
user1.Id = 6
user1.Name = "James"
user2 := BeegoUser{}
user2.Id =12
user2.Name = "Wade"
_,err1 := o.Update(&user1)
_,err2 := o.Insert(&user2)
if err1 !=nil || err2 != nil{
o.Rollback()
}else {
o.Commit()
}
}
orm.Debug = true
var w io.Writer
orm.DebugLog = orm.NewLog(w)