1
0
Fork 0
empact/db/common.go

43 lines
725 B
Go
Raw Normal View History

2015-03-04 19:09:08 +00:00
package db
import (
2015-03-05 12:53:38 +00:00
"fmt"
2015-03-05 16:06:45 +00:00
"strings"
2015-03-04 19:14:11 +00:00
_ "github.com/go-sql-driver/mysql"
2015-03-05 16:06:45 +00:00
"github.com/jmoiron/sqlx"
"github.com/jmoiron/sqlx/reflectx"
2015-03-04 19:09:08 +00:00
)
var (
2015-03-05 16:06:45 +00:00
conn *sqlx.DB
stmts map[string]*sqlx.Stmt
2015-03-04 19:09:08 +00:00
)
2015-03-05 16:06:45 +00:00
func Connect(params string) (err error) {
conn, err = sqlx.Connect("mysql", params)
conn.Mapper = reflectx.NewMapperFunc("json", strings.ToLower)
stmts = map[string]*sqlx.Stmt{}
2015-03-04 19:09:08 +00:00
return
}
2015-03-05 16:06:45 +00:00
func stmt(query string) *sqlx.Stmt {
2015-03-04 19:09:08 +00:00
if stmt, ok := stmts[query]; ok {
return stmt
} else {
stmt := prepareStatement(query)
stmts[query] = stmt
return stmt
}
}
2015-03-05 16:06:45 +00:00
func prepareStatement(query string) *sqlx.Stmt {
if stmt, err := conn.Preparex(query); err == nil {
2015-03-04 19:09:08 +00:00
return stmt
} else {
2015-03-05 12:53:38 +00:00
fmt.Println(query)
2015-03-04 19:09:08 +00:00
panic(err)
}
}