• 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)
    }
  • 相关阅读:
    Asp.Net服务器Cassini
    Vista系统Administrator帐户的激活与禁用
    SqlServer中的Top * With Ties
    SqlServer建远程服务连接
    SqlServer2005安装成功后补加Sa用户
    列出某个表中所有的列名
    水晶报表周期性打开报表失败
    Asp.net中文cookie的乱码问题
    HTML数据库编程、JavaScript数据库编程
    试图索引的限制
  • 原文地址:https://www.cnblogs.com/lijunhao/p/12287212.html
Copyright © 2020-2023  润新知