You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
starainrt/database.go

132 lines
2.5 KiB
Go

package starainrt
import (
"database/sql"
"errors"
"strconv"
)
func FetchAll(rows *sql.Rows) (error, map[int]map[string]string) {
var ii int = 0
records := make(map[int]map[string]string)
columns, err := rows.Columns()
if err != nil {
return err, records
}
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}
for rows.Next() {
if err := rows.Scan(scanArgs...); err != nil {
return err, records
}
record := make(map[string]string)
for i, col := range values {
switch vtype := col.(type) {
case float64:
record[columns[i]] = strconv.FormatFloat(vtype, 'f', -1, 64)
case int64:
record[columns[i]] = strconv.FormatInt(vtype, 10)
case string:
record[columns[i]] = vtype
default:
record[columns[i]] = string(vtype.([]byte))
}
}
records[ii] = record
ii++
}
return nil, records
}
func OpenDB(Method, ConnStr string) error {
var err error
DBRes, err = sql.Open(Method, ConnStr)
if err != nil {
return err
}
err = DBRes.Ping()
return err
}
func CloseDB() {
DBRes.Close()
DBRows.Close()
}
func Query(args ...interface{}) (error, map[int]map[string]string) {
var err error
records := make(map[int]map[string]string)
if err = DBRes.Ping(); err != nil {
return err, records
}
if len(args) == 0 {
return errors.New("no args"), records
}
if len(args) == 1 {
sql := args[0]
if DBRows, err = DBRes.Query(sql.(string)); err != nil {
return err, records
}
return FetchAll(DBRows)
}
sql := args[0]
stmt, err := DBRes.Prepare(sql.(string))
defer stmt.Close()
if err != nil {
return err, records
}
var para []interface{}
for k, v := range args {
if k != 0 {
switch vtype := v.(type) {
default:
para = append(para, vtype)
}
}
}
if DBRows, err = stmt.Query(para...); err != nil {
return err, records
}
return FetchAll(DBRows)
}
func DBExec(args ...interface{}) error {
var err error
if err = DBRes.Ping(); err != nil {
return err
}
if len(args) == 0 {
return errors.New("no args")
}
if len(args) == 1 {
sql := args[0]
if _, err = DBRes.Exec(sql.(string)); err != nil {
return err
}
return nil
}
sql := args[0]
stmt, err := DBRes.Prepare(sql.(string))
defer stmt.Close()
if err != nil {
return err
}
var para []interface{}
for k, v := range args {
if k != 0 {
switch vtype := v.(type) {
default:
para = append(para, vtype)
}
}
}
if _, err = stmt.Exec(para...); err != nil {
return err
}
return nil
}