go 封装MySQL

//first need to download golang mysql driver package and smartDB package

首先下载golang mysql 驱动包和 smartDB包

go get github.com/go-sql-driver/mysql

go get github.com/marco2013/smartDB       //DB源代码,封装了mysql连接,以及增删改查几个基本接口,查询包括json格式的返回

//second use this package in your projects

然后就可以在你的项目中使用该包了, 欢迎提出宝贵意见哈

github链接地址



使用

// smartDbTest
package main

import (
	"fmt"
	"github.com/marco2013/smartDB"
)

func main() {
	fmt.Println("Hello World!")

	db, err := smartDB.NewDb("mysql", "root:root123@tcp(192.168.1.14:3306)/test?charset=utf8")
	if err != nil {
		fmt.Println("打开SQL时出错:", err.Error())
		return
	}
	defer db.Close()

	//查询数据,指定字段名,返回sql.Rows结果集
	rows, _ := db.Query("select id,name from person")
	id := 0
	name := ""
	for rows.Next() {
		rows.Scan(&id, &name)
		fmt.Println(id, name)
	}
	defer rows.Close()

	//查询数据,取所有字段
	rows2, err := db.Query("select * from person")
	if err != nil {
		fmt.Println("fetch rows error:", err)
		return
	}
	defer rows2.Close()
	//返回所有列
	cols, err := rows2.Columns()
	if err != nil {
		fmt.Println("fetch column error:", err)
		return
	}
	//这里表示一行所有列的值,用[]byte表示
	vals := make([][]byte, len(cols))
	//这里表示一行填充数据
	scans := make([]interface{}, len(cols))
	//这里scans引用vals,把数据填充到[]byte里
	for k, _ := range vals {
		scans[k] = &vals[k]
	}

	i := 0
	result := make(map[int]map[string]string)
	for rows2.Next() {
		//填充数据
		rows2.Scan(scans...)
		//每行数据
		row := make(map[string]string)
		//把vals中的数据复制到row中
		for k, v := range vals {
			key := cols[k]
			//这里把[]byte数据转成string
			row[key] = string(v)
		}
		//放入结果集
		result[i] = row
		i++
	}
	fmt.Println(result)

	JsonOut := db.QueryDataRowsToJson("select * from person")
	fmt.Println("JsonOut:%s", JsonOut)

	//instid, err := db.Insert("insert into person(id,name,age) values(null, 'jack',22)")
	instid, err := db.Insert("insert into person(id,name,age) values(null, 'jack',22)")
	if err != nil {
		fmt.Println("insert SQL时出错:", err.Error())
		return
	}
	fmt.Println("insert SQL id:%d", instid)
	//affNum, err := db.Update("update person set age=? where name=?", 100, "jack")
	affNum, err := db.Update("update person set age=100 where name='jack'")
	if err != nil {
		fmt.Println("update SQL时出错:", err.Error())
		return
	}
	fmt.Println("update SQL affected num:%d", affNum)
	affNum, err = db.Delete("delete from person where name=?", "jack")
	if err != nil {
		fmt.Println("delete SQL时出错:", err.Error())
		return
	}
	fmt.Println("delete SQL affected num:%d", affNum)

}



附上 package源码:

// smartDB project smartDB.go
package smartDB
import (
 "database/sql"
 "encoding/json"
 _ "github.com/go-sql-driver/mysql"
)
type MyDb struct {
 *sql.DB
}
func NewDb(driverName, dataSourceName string) (*MyDb, error) {
 db, err := sql.Open(driverName, dataSourceName)
 if err != nil {
  return nil, err
 }
 mydb := &MyDb{DB: db}
 return mydb, nil
}
func (this *MyDb) Query(query string, args ...interface{}) (*sql.Rows, error) {
 r, err := this.DB.Query(query, args...)
 if err != nil {
  return nil, err
 }
 return r, nil
}
//queryRows2Json
func (this *MyDb) QueryDataRowsToJson(query string, args ...interface{}) string {
 rows, err := this.Query(query, args...)
 if err != nil {
  return ""
 }
 defer rows.Close()
 columns, err := rows.Columns()
 if err != nil {
  //fmt.Println("row to json:", err)
  return ""
 }
 count := len(columns)
 tableData := make([]map[string]interface{}, 0)
 values := make([]interface{}, count)
 valuePtrs := make([]interface{}, count)
 for rows.Next() {
  for i := 0; i < count; i++ {
   valuePtrs[i] = &values[i]
  }
  rows.Scan(valuePtrs...)
  entry := make(map[string]interface{})
  for i, col := range columns {
   var v interface{}
   val := values[i]
   b, ok := val.([]byte)
   if ok {
    v = string(b)
   } else {
    v = val
   }
   entry[col] = v
  }
  tableData = append(tableData, entry)
 }
 jsonData, err := json.Marshal(tableData)
 if err != nil {
  //fmt.Println("2 row to json:", err)
  return ""
 }
 //fmt.Println(string(jsonData))
 return string(jsonData)
}
/*format:  insert into test(id,name) values(null, '444') */
func (this *MyDb) Insert(strSql string) (int64, error) {
 result, err := this.Exec(strSql)
 if err != nil {
  return 0, err
 }
 ins_id, _ := result.LastInsertId()
 return ins_id, nil
}
/*根据主键更新数据记录,返回所影响的行数
("update test set name = '000' where id > ?", 2); */
func (this *MyDb) Update(strSql string, args ...interface{}) (int64, error) {
 result, err := this.Exec(strSql, args...)
 if err != nil {
  return 0, err
 }
 var affNum int64
 affNum, err = result.RowsAffected()
 if err != nil {
  return 0, err
 }
 return affNum, nil
}
/*根据主键删除一条数据,返回所影响的行
("delete from test where id = ?", 3); */
func (this *MyDb) Delete(strSql string, args ...interface{}) (int64, error) {
 result, err := this.Exec(strSql, args...)
 if err != nil {
  return 0, err
 }
 var affNum int64
 affNum, err = result.RowsAffected()
 if err != nil {
  return 0, err
 }
 return affNum, nil
}



你可能感兴趣的:(程序点滴)