44

golang gorm 操作mysql

 5 years ago
source link: https://studygolang.com/articles/16301?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

golang 官方的那个操作mysql的有点麻烦所以就使用了gorm,下面就gorm的使用做下简单介绍

下载gorm:

go get -u github.com/jinzhu/gorm

在项目中引入gorm:

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

定义db连接信息

func DbConn(MyUser, Password, Host, Db string, Port int) *gorm.DB {
    connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",  MyUser,Password, Host, Port, Db )
    db, err := gorm.Open("mysql", connArgs)
    if err != nil {
        log.Fatal(err)
    }
    db.SingularTable(true)
    return db
}

由于grom是使用的orm映射,所以需要定义要操作的表的model,在go中需要定义一个struct, struct的名字就是对应数据库中的表名,注意gorm查找struct名对应数据库中的表名的时候会默认把你的struct中的大写字母转换为小写并加上“s”,所以可以加上 db.SingularTable(true) 让grom转义struct名字的时候不用加上s。我是提前在数据库中创建好表的然后再用grom去查询的,也可以用gorm去创建表,我感觉还是直接在数据库上创建,修改表字段的操作方便,grom只用来查询和更新数据。

假设数据库中的表已经创建好,下面是数据库中的建表语句:

CREATE TABLE `xz_auto_server_conf` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `group_zone` varchar(32) NOT NULL COMMENT '大区例如:wanba,changan,aiweiyou,360',
  `server_id` int(11) DEFAULT '0' COMMENT '区服id',
  `server_name` varchar(255) NOT NULL COMMENT '区服名称',
  `open_time` varchar(64) DEFAULT NULL COMMENT '开服时间',
  `service` varchar(30) DEFAULT NULL COMMENT '环境,test测试服,formal混服,wb玩吧',
  `username` varchar(100) DEFAULT NULL COMMENT 'data管理员名称',
  `submit_date` datetime DEFAULT NULL COMMENT '记录提交时间',
  `status` tinyint(2) DEFAULT '0' COMMENT '状态,0未处理,1已处理,默认为0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

定义model,即struct, 定于struct时我们可以只定义我们需要从数据库中取回的特定字段:

gorm在转义表名的时候会把stuct的大写字母(首字母除外) 替换成“_”,所以下面的"XzAutoServerConf "会转义成数数据库中对应“xz_auto_server conf”的表名, 对应的字段名的查找会先按照tag里面的名称去里面查找,如果没有定义标签则按照struct定义的字段查找,查找的时候struct字段中的大写会被转义成“ ”,例“GroupZone”会去查找表中的group_zone字段

//定义struct
type XzAutoServerConf struct {
    GroupZone string  `gorm:"column:group_zone"`
    ServerId  int
    OpenTime  string
    ServerName string
    Status    int
}

//定义数据库连接
type ConnInfo struct {
    MyUser string
    Password string
    Host string
    Port int
    Db string
}

func main () {
cn := ConnInfo{
        "root",
        123456",
        "127.0.0.1",
        3306,
        "xd_data",
    }
     db := DbConn(cn.MyUser,cn.Password,cn.Host,cn.Db,cn.Port)
     defer db.Close()  // 关闭数据库链接,defer会在函数结束时关闭数据库连接
    var rows []api.XzAutoServerConf
//select 
db.Where("status=?", 0).Select([]string{"group_zone", "server_id", "open_time", "server_name"}).Find(&rows)
//update
    err := db.Model(&rows).Where("server_id=?", 80).Update("status", 1).Error
    if err !=nil {
    fmt.Println(err)
    }
fmt.Println(rows)
}

更多grom操作可以参考: https://jasperxu.github.io/gorm-zh/


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK