MySQL工具类

 1 package tools
 2 
 3 
 4 import (
 5     "database/sql"
 6     "fmt"
 7     _"github.com/go-sql-driver/mysql"
 8 )
 9 
10 type MySQLHelper struct {
11     Connection string
12 }
13 
14 func (t *MySQLHelper) GetDb()*sql.DB{
15     db, err := sql.Open("mysql", t.Connection)
16     if err != nil {
17         fmt.Println(err)
18     }
19     return db
20 }
21 
22 //region 查询数据集合,返回rows对象指针
23 func (t *MySQLHelper) Query(sqlstr string)*sql.Rows{
24     db:=t.GetDb()
25     //关闭数据库
26     defer db.Close()
27 
28     rows,err := db.Query(sqlstr)
29     if err!=nil{
30         msg:=fmt.Sprintf("Query-SQL异常:%s",sqlstr)
31         fmt.Println(msg)
32         LogTool.Log(msg,4,err)
33         return nil
34     }
35     return rows
36 }
37 //endregion
38 
39 //region 查询数据集合,返回rows对象指针
40 func (t *MySQLHelper) ExecuteSQL(sqlstr string)(ret sql.Result,err error){
41     db:=t.GetDb()
42     //关闭数据库
43     defer db.Close()
44 
45     ret,err = db.Exec(sqlstr)
46     if err!=nil{
47         msg:=fmt.Sprintf("Execute-SQL异常:%s",sqlstr)
48         fmt.Println(msg)
49         LogTool.Log(msg,4,err)
50     }
51     return ret,err
52 }
53 //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)
}

 

posted on 2020-02-09 15:05  李军浩  阅读(741)  评论(0编辑  收藏  举报

导航