MySQL工具类

package tools


import (
    "database/sql"
    "fmt"
    _"github.com/go-sql-driver/mysql"
)

type MySQLHelper struct {
    Connection string
}

func (t *MySQLHelper) GetDb()*sql.DB{
    db, err := sql.Open("mysql", t.Connection)
    if err != nil {
        fmt.Println(err)
    }
    return db
}

//region 查询数据集合,返回rows对象指针
func (t *MySQLHelper) Query(sqlstr string)*sql.Rows{
    db:=t.GetDb()
    //关闭数据库
    defer db.Close()

    rows,err := db.Query(sqlstr)
    if err!=nil{
        msg:=fmt.Sprintf("Query-SQL异常:%s",sqlstr)
        fmt.Println(msg)
        LogTool.Log(msg,4,err)
        return nil
    }
    return rows
}
//endregion

//region 查询数据集合,返回rows对象指针
func (t *MySQLHelper) ExecuteSQL(sqlstr string)(ret sql.Result,err error){
    db:=t.GetDb()
    //关闭数据库
    defer db.Close()

    ret,err = db.Exec(sqlstr)
    if err!=nil{
        msg:=fmt.Sprintf("Execute-SQL异常:%s",sqlstr)
        fmt.Println(msg)
        LogTool.Log(msg,4,err)
    }
    return ret,err
}
//endregion

调用示例:

var MySQLTool tools.MySQLHelper
MySQLTool.Connection=ConfigTool.Gateway_Connection
//insert or update or delete
ret,err:=MySQLTool.ExecuteSQL(sqlstr)

//query
rows:=MySQLTool.Query(sqlstr)
var model entity.GatewayProject
for rows.Next(){
err:=rows.Scan(&model.Id,&model.ProjectName,&model.Prefix,&model.ProjectType,&model.ProjectPath,&model.ProjectMemo)
list = append(list, model)
}

相关推荐