前端之家收集整理的这篇文章主要介绍了
Golang1.7.4标准库sql使用,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
import (
"database/sql"
"errors"
"fmt"
"net"
"sync/atomic"
"time"
"github.com/go-sql-driver/MysqL"
)
func main() {}
func NewMysqL(connstr string,maxopen int) (*_MysqL,error) {
m := &_MysqL{connstr: connstr,maxopen: maxopen}
err := m.dial()
return m,err
}
var UnavailableError = errors.New("Status Unavailable")
type _MysqL struct {
connstr string
maxopen int
db *sql.DB
status uint32
}
func (s *_MysqL) init() error {
db,err := sql.Open("MysqL",s.connstr)
if err != nil {
return err
}
if s.maxopen <= 0 {
db.SetMaxOpenConns(20)
} else {
db.SetMaxOpenConns(s.maxopen)
}
s.db = db
return nil
}
func (s *_MysqL) dial() error {
if s.db == nil {
err := s.init()
if err != nil {
return err
}
}
var rtime time.Duration = 10
redial:
err := s.db.Ping()
if err != nil {
if _,ok := err.(*MysqL.MysqLError); ok {
return err
}
if isNetError(err) {
<-time.After(rtime * time.Second)
if rtime < 120 {
rtime += 10
}
fmt.Println(err)
goto redial
}
return err
}
s.SetStatus(1)
return nil
}
func (s *_MysqL) Reset(connstr string,maxopen int) error {
db,connstr)
if err != nil {
return err
}
if maxopen <= 0 {
db.SetMaxOpenConns(20)
} else {
db.SetMaxOpenConns(maxopen)
}
err = db.Ping()
if err != nil {
return err
}
s.connstr = connstr
s.maxopen = maxopen
tmpdb := s.db
s.db = db
tmpdb.Close()
return nil
}
func (s *_MysqL) Exec(query string,args ...interface{}) (sql.Result,error) {
if s.Status() {
result,err := s.db.Exec(query,args...)
if err != nil {
if isNetError(err) {
s.SetStatus(0)
if err = s.dial(); err == nil {
return s.Exec(query,args...)
}
return nil,err
}
}
return result,err
}
return nil,UnavailableError
}
func (s *_MysqL) Query(query string,args ...interface{}) (*sql.Rows,error) {
if s.Status() {
rows,err := s.db.Query(query,args...)
if err != nil {
if isNetError(err) {
s.SetStatus(0)
if err = s.dial(); err == nil {
return s.Query(query,err
}
}
return rows,UnavailableError
}
func (s *_MysqL) Status() bool {
return atomic.LoadUint32(&s.status) != 0
}
func (s *_MysqL) SetStatus(status uint32) {
atomic.StoreUint32(&s.status,status)
}
func (s *_MysqL) Close() {
if s.db != nil {
s.db.Close()
}
}
func isNetError(err error) bool {
_,ok := err.(*net.OpError)
return ok
}
原文链接:https://www.f2er.com/go/188955.html