Golang实现mysql读库映射成Map【Easy】

这个类库灵感来源于.net的dbHelper类,因为其简单易用,现在go的driver必须使用对象映射,这让人火大不爽,不能实现灵活的Map,在Key经常变动的业务场景里面非常不爽,我还是喜欢直接写sql来的爽,无处不在,搞神马映射感觉约束!所以写了这个类库!

对于这个driver映射一个map还是可以轻松到到了,关键时map里面的数据全是byte,这几乎很难解码,所以封装类库,实现整体的解决方法,大家用的不好的地方,欢迎留言,完善!多谢!多谢!

获取类库的方法:

1、git clone [email protected]:bobby96333/GoSqlHelper.git
2、go get github.com/bobby96333/GoShellHelper

代码 Demo

package main

import (
"fmt"
"github.com/bobby96333/goSqlHelper"
)

func main(){
fmt.Println("hello")
conn,err :=goSqlHelper.MysqlOpen("user:password@tcp(127.0.0.1:3306)/dbname")
checkErr(err)
row,err := conn.QueryRow("select * from table where col1 = ? and col2 = ?","123","abc")
checkErr(err)
if *row==nil {
fmt.Println("no found row")
}else{
fmt.Printf("%+v",row)
}
}

func checkErr(err error){
if err!=nil {
panic(err)
}
}

output:
&map[col1:abc col2:123]

HelperRow的使用方法

fmt.println(row.ToJson())
fmt.Println("get string:",row.String("col2"))

//query a integer
fmt.Println("get Int:",row.PInt("col1"))
//or
if col1,err:=row.Int("col1");err!=nil {
fmt.Println("query col 1 :",col1)
}

//query a long
fmt.Println("get Int:",row.PInt64("col1"))
//or
if col1,err:=row.Int64("col1");err!=nil {
fmt.Println("query col 1 :",col1)
}

 多行数据读取

rows,err := conn.QueryRows("select * from table where col1 = ? and col2 = ?","123","abc")
errCheck(err)
for _,row :=range *rows {
fmt.Println("row:",row.ToJson())
}

 数据流方式读取

querying,err := conn.Querying("select * from table where col1 = ? and col2 = ?","123","abc")
errCheck(err)
for row,err:=querying.QueryRow();row!=nil&&err==nil;row,err=querying.QueryRow() {
fmt.Println("row:",row.ToJson())
}

 执行sql

ret,err := conn.Exec("updatetable set col2 = ? where col1 = ? ","abc","123")
errCheck(err)
rowNum,err:= ret.RowsAffected()
errCheck(err)
fmt.Println("updated row:",rowNum)

猜你喜欢

转载自www.cnblogs.com/a-xu/p/10642722.html