首页 资讯 社群 我的社区 搜索

Go 中操作 MySQL

linux5.net
2018-09-18 23:21:40

一些项目中还是会用到关系型数据库,就像mysql 就我们经常用的。在 go 中使用mysql 引擎是 go-sql-driver (相当于JAVA 中的 JDBC)

同样按MVC 的规范,定义models 层,在这里 实现 dao

创建一个单例的连接,尽量避免频繁的连接断开:


Go
package models

import (
   "database/sql"
   _ "github.com/go-sql-driver/mysql"
   //"gopkg.in/mgo.v2"
   "fmt"

   "errors"
)

const (
   dbhostsip  = "localhost:3306"
   dbusername = "root"
   dbpassword = "root"
   dbname     = "deepinCinfo"
)

type Dao struct {
   session *sql.DB
}

var _dbConnection *sql.DB = nil

func init() {

   fmt.Println("====================== DB init() _dbConnection =========================")

   ss := dbusername + ":" + dbpassword + "@tcp(" + dbhostsip + ")/" + dbname + "?charset=utf8"
   fmt.Println(ss)
   db, err := sql.Open("mysql", ss)

   if err == nil {

      db.SetMaxOpenConns(150)
      db.SetMaxIdleConns(50)

      db.Ping()
      _dbConnection = db
   }

}

func OpenDao() (*Dao, error) {

   fmt.Println("============================ OpenDao() ==========================")

   if _dbConnection != nil {

      return &Dao{_dbConnection}, nil
   }

   return nil, errors.New("-1")
}


models 自己封装一组方法实现对 表的增、删、改、查; mysql 可以支持标准的 SQL 语句,一点不带坑; 

Go
func (dao *Dao) ReadClientInfo(clientInfo RUser_Info) RUser_InfoList {
   /*
      sqlStr := "select ClientMAC,max(BootTime)  as BootTime ,max(CloseTime) as CloseTime" +
            " from RUserInfo WHERE WorkUnit=" +  strconv.Itoa( clientInfo.WorkUnit ) +" group by ClientMAC;"
   */

   sqlStr := "SELECT * FROM ClientTable WHERE WorkUnit='" + clientInfo.WorkUnit + "';"
   fmt.Println(sqlStr)

   rows, _ := dao.session.Query(sqlStr)
   defer rows.Close()

   ruser_infolist := RUser_InfoList{}

   for rows.Next() {

      ruser_info := RUser_Info{}

      err := rows.Scan(&ruser_info.ID,
         &ruser_info.LicenseStatus,
         &ruser_info.ClientMAC,
         &ruser_info.Address,
         &ruser_info.Netmask,
         &ruser_info.Broadcast,
         &ruser_info.LinuxInfo,
         &ruser_info.DeepinInfo,
         &ruser_info.PrintInfo,
         &ruser_info.VGAinfo,
         &ruser_info.Meminfo,
         &ruser_info.Cpuinfo,
         &ruser_info.Hostname,
         &ruser_info.LoginUser,
         &ruser_info.Region,
         &ruser_info.WorkUnit,
         &ruser_info.SignID,
         &ruser_info.BootTime,
         &ruser_info.CloseTime,
         &ruser_info.Uleng,
         &ruser_info.WorkLog )

      if err != nil {

         fmt.Println("***" ,err )
      }

      ruser_infolist.RUser_Infos = append(ruser_infolist.RUser_Infos, ruser_info)
   }

   return ruser_infolist
}


MVC 规范再来写一个Controllers ,在Controllers 中来调用 models 中封装的方法;

Go
func (c UserInfo) ReadClientInfo() revel.Result {

   work_id := c.Params.Get("work_id")

   dao, err := models.OpenDao()
   if dao == nil || err != nil {
      c.Response.Status = 500
      return c.RenderError(errors.New("500"))

   }
   defer dao.Close()

   clientInfo := models.RUser_Info{}

   clientInfo.WorkUnit = work_id

   HH := dao.ReadClientInfo(clientInfo)
   return c.RenderJSON(HH)
}
用户评论