操作sql类,目前只有一个查询,其他可以根据这个再去扩展
package QORM
import (
"database/sql"
"fmt"
"reflect"
_ "github.com/go-sql-driver/mysql"
)
//请求结构体
type QDBProto struct {
DB *sql.DB
}
var qDBProto *QDBProto
//构造函数
func CreateDBProto(driver string, sqlLink string) *QDBProto {
qDBProto = new(QDBProto)
db, err := sql.Open(driver, sqlLink)
if err == nil {
qDBProto.DB = db
return qDBProto
} else {
return nil
}
}
//查询
func (p *QDBProto) Select(destClass interface{}, sqlstr string, arg ...interface{}) ([]interface{}, int) {
var rowCount int = 0
var rows *sql.Rows
var err error
if arg != nil {
rows, err = p.DB.Query(sqlstr)
} else {
rows, err = p.DB.Query(sqlstr, arg)
}
if err != nil {
fmt.Println(err.Error())
return nil, rowCount
}
defer rows.Close()
result := make([]interface{}, 0)
for rows.Next() {
scanArr := make([]interface{}, 0)
scanEntity := make(map[string]interface{})
destValue := reflect.ValueOf(destClass)
destType := reflect.TypeOf(destClass)
fieldCount := destValue.NumField()
for fieldIndex := 0; fieldIndex < fieldCount; fieldIndex++ {
field := destValue.Field(fieldIndex)
fieldType := field.Type()
newFieldValue := reflect.New(fieldType)
fieldValue := newFieldValue.Interface()
scanArr = append(scanArr, fieldValue)
fmt.Println(destType.Field(fieldIndex).Name)
scanEntity[destType.Field(fieldIndex).Name] = fieldValue
}
if err := rows.Scan(scanArr...); err != nil {
fmt.Println(err.Error())
return nil, rowCount
} else {
result = append(result, scanEntity)
rowCount++
}
}
return result, rowCount
}
使用:
rows, rowCount := conn2.Select(automethodNew{}, "select * from automethod")
有疑问加站长微信联系(非本文作者)