zoukankan      html  css  js  c++  java
  • 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)
    }
  • 相关阅读:
    【iOS】ARC & MRC
    【iOS】判断苹果的设备是哪种
    【iOS】获取项目名和版本号
    CSDN Markdown 超链接
    【iOS】安装 CocoaPods
    【Android Studio】常用快捷键
    Linux初接触设置笔记01
    Java循环输出一个菱形与阶乘倒数
    对象的声明与实例化(转)
    Java堆/栈/常量池以及String的详细详解(转)------经典易懂系统
  • 原文地址:https://www.cnblogs.com/lijunhao/p/12287212.html
Copyright © 2011-2022 走看看