golang 基于go-sql-driver的增删改查的简单封装

前端之家收集整理的这篇文章主要介绍了golang 基于go-sql-driver的增删改查的简单封装前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

建一个简单的test表


CREATE TABLE `test` (
 `a` int(11) NOT NULL AUTO_INCREMENT,`b` int(11) DEFAULT NULL,PRIMARY KEY (`a`)
) ENGINE=InnoDB AUTO_INCREMENT=157


package main

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

func main() {
	db,err := sql.Open("MysqL","root:@tcp(127.0.0.1:3306)/test?charset=utf8")
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()

	rows,_ := fetchRows(db,"SELECT * FROM test")
	for _,v := range *rows {
		fmt.Println(v["a"],v["b"])
	}
	fmt.Println(insert(db,"INSERT INTO test( b ) VALUES( ? )",1))
	row,_ := fetchRow(db,"SELECT * FROM test where a = ?",1)
	fmt.Println(*row)
}

//插入
func insert(db *sql.DB,sqlstr string,args ...interface{}) (int64,error) {
	stmtIns,err := db.Prepare(sqlstr)
	if err != nil {
		panic(err.Error())
	}
	defer stmtIns.Close()

	result,err := stmtIns.Exec(args...)
	if err != nil {
		panic(err.Error())
	}
	return result.LastInsertId()
}

//修改删除
func exec(db *sql.DB,err := stmtIns.Exec(args...)
	if err != nil {
		panic(err.Error())
	}
	return result.RowsAffected()
}

//取一行数据,注意这类取出来的结果都是string 
func fetchRow(db *sql.DB,args ...interface{}) (*map[string]string,error) {
	stmtOut,err := db.Prepare(sqlstr)
	if err != nil {
		panic(err.Error())
	}
	defer stmtOut.Close()

	rows,err := stmtOut.Query(args...)
	if err != nil {
		panic(err.Error())
	}

	columns,err := rows.Columns()
	if err != nil {
		panic(err.Error())
	}

	values := make([]sql.RawBytes,len(columns))
	scanArgs := make([]interface{},len(values))
	ret := make(map[string]string,len(scanArgs))

	for i := range values {
		scanArgs[i] = &values[i]
	}
	for rows.Next() {
		err = rows.Scan(scanArgs...)
		if err != nil {
			panic(err.Error())
		}
		var value string

		for i,col := range values {
			if col == nil {
				value = "NULL"
			} else {
				value = string(col)
			}
			ret[columns[i]] = value
		}
		break //get the first row only
	}
	return &ret,nil
}

//取多行,<span style="font-family: Arial,Helvetica,sans-serif;">注意这类取出来的结果都是string </span>
func fetchRows(db *sql.DB,args ...interface{}) (*[]map[string]string,len(values))

	ret := make([]map[string]string,0)
	for i := range values {
		scanArgs[i] = &values[i]
	}

	for rows.Next() {
		err = rows.Scan(scanArgs...)
		if err != nil {
			panic(err.Error())
		}
		var value string
		vmap := make(map[string]string,len(scanArgs))
		for i,col := range values {
			if col == nil {
				value = "NULL"
			} else {
				value = string(col)
			}
			vmap[columns[i]] = value
		}
		ret = append(ret,vmap)
	}
	return &ret,nil
}
原文链接:https://www.f2er.com/go/190828.html

猜你在找的Go相关文章