gorm系列-简单入门

简介

GORM系列:b站搜七米

文档:https://www.liwenzhou.com/posts/Go/gorm/

什么是ORM:Object(对象) Relational(关系) Mapping(映射)

对象:程序中的对象/实例 例如Go中的结构体实例

关系:关系数据库 例如MySQL

gorm的官方文档:https://gorm.io/zh_CN/docs/

案例

举个不用gorm的例子

type UserInfo struct {
	ID uint
	Name string
	Gender string
	Hobby string
}

func main()  {
	u1 := UserInfo{1, "zisefeizhu", "男","篮球"}
	//将u1数据存入数据库
	insert into userinfo values(1, "紫色飞猪","男","篮球");  //sql语句
}

要求开发不仅会go还要熟练掌握sql语句

使用gorm的例子

type UserInfo struct {
	ID uint
	Name string
	Gender string
	Hobby string
}

func main()  {
	u1 := UserInfo{1, "zisefeizhu", "男","篮球"}
	//将u1数据存入数据库
	orm.Create(&u1)   //orm语句不要太简单  
}

ORM优缺点

优点:提高开发效率

缺点:牺牲执行性能、牺牲灵活性、弱化SQL能力

入门

安装gorm

E:\gostudent\gin\lesson19>go get -u github.com/jinzhu/gorm

**安装mysql ** 下载地址:https://dev.mysql.com/downloads/mysql/

  1. 解压到指定目录, 例如:E:\mysql

  2. 管理员cmd到bin目录 例如:E:\mysql\mysql-8.0.19-winx64\bin

  3. 执行: mysqld --initialize --console 记下密码:-YML?i2uo7gz(密码随机生成,每次密码不一样,如果没记住,删掉data文件夹,重新执行该命令)

  4. 创建mysql8服务:mysqld --install mysql8

  5. 启动mysql8:net start mysql8

  6. 登陆修改密码

    e:\mysql\mysql-8.0.19-winx64\bin>mysql -uroot -p
    Enter password: ************
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 8
    Server version: 8.0.19
    
    Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY '123456';
    Query OK, 0 rows affected (0.22 sec)
    
    mysql> flush privileges;
    Query OK, 0 rows affected (0.06 sec)
    mysql> exit
    Bye
    e:\mysql\mysql-8.0.19-winx64\bin>mysql -uroot -p
    Enter password: 123456
    
  7. windows环境变量设置

  8. SQLyog连接

    mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456';  #修改加密规则
    mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456'; #修改密码加密策略
    Query OK, 0 rows affected (0.06 sec)
    
    mysql> flush privileges;  #刷新权限
    Query OK, 0 rows affected (0.04 sec)
    


GORM基本示例

使用SQLyog Professional 64 学习

package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

//UserInfo -->数据表
type UserInfo struct {
	ID int
	Name string
	Gender string
	Hobby string
}
func main() {
	//连接MySQL数据库
	//方法1
	//connArgs := fmt.Sprintf("%s:%s@%s(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", "root","123456", "tcp","127.0.0.1", 3306, "db" )
	//db, err := gorm.Open("mysql", connArgs)
	//方法2    一定要细心啊
	db, err := gorm.Open("mysql","root:123456@tcp(127.0.0.1:3306)/db?charset=utf8mb4&parseTime=True&loc=Local")
	//panic: dial tcp [::1]:3306: connectex: No connection could be made because the target machine actively refused it. 数据库没打开 被拒绝

	if err != nil{
		panic(err)
	}
	defer db.Close()

	//创建表 自动迁移(把结构体和数据表进行对应)
	db.AutoMigrate(&UserInfo{})

	//创建数据行
	u1 := UserInfo{3, "紫色飞猪","男","直播"}
	db.Create(&u1)
}


简单的增删改查

package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

//UserInfo -->数据表
type UserInfo struct {
	ID int
	Name string
	Gender string
	Hobby string
}
func main() {
	//连接MySQL数据库
	//方法1
	//connArgs := fmt.Sprintf("%s:%s@%s(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", "root","123456", "tcp","127.0.0.1", 3306, "db" )
	//db, err := gorm.Open("mysql", connArgs)
	//方法2    一定要细心啊
	db, err := gorm.Open("mysql","root:123456@tcp(127.0.0.1:3306)/db?charset=utf8mb4&parseTime=True&loc=Local")
	//panic: dial tcp [::1]:3306: connectex: No connection could be made because the target machine actively refused it. 数据库没打开 被拒绝

	if err != nil{
		panic(err)
	}
	defer db.Close()

	//创建表 自动迁移(把结构体和数据表进行对应)
	db.AutoMigrate(&UserInfo{})

	////创建数据行
	//u1 := UserInfo{3, "紫色飞猪","男","直播"}
	//db.Create(&u1)

	//查询
	var u UserInfo
	db.First(&u)   //查询一行
	fmt.Printf("u:%#v\n",u)
	var u1 UserInfo
	db.Last(&u1)   //查询最后一行
	fmt.Printf("u1:%#v\n",u1)
	//更新
	db.Model(&u).Update("hobby","双色球")
	//删除
	db.Delete(&u).Delete("")
}
posted @ 2020-04-21 20:05  紫色飞猪  阅读(2229)  评论(0编辑  收藏  举报