package orm

import (
	"bswas/utilities"
	"database/sql"
)

func query(sqlStr string,db *sql.DB)(list []map[string]string) {
	rows,err := db.Query(sqlStr)
	if err != nil {
		utilities.WriteLog("/orm/query.go:11   SQL执行错误!("+sqlStr+")","ERROR")
		return
	}
	//字段名称
	columns, _ := rows.Columns()
	//多少个字段
	length := len(columns)
	//每一行字段的值
	values := make([]sql.RawBytes, length)
	//保存的是values的内存地址
	pointer := make([]interface{}, length)
	for i := 0; i < length; i++ {
		pointer[i] = &values[i]
	}
	for rows.Next() {
		//把参数展开，把每一行的值存到指定的内存地址去，循环覆盖，values也就跟着被赋值了
		err := rows.Scan(pointer...)
		if err != nil {
			utilities.WriteLog("/orm/query.go:31   结果集转换错误!("+sqlStr+")","ERROR")
			return
		}
		//每一行
		row := make(map[string]string)
		for i := 0; i < length; i++ {
			row[columns[i]] = string(values[i])
		}
		list = append(list, row)
	}
	_ = rows.Close()
	return
}
func GetMysqlData(sqlStr string)(list []map[string]string) {
	db, err := utilities.Mysql()
	if err != nil {
		utilities.WriteLog("/orm/query.go:47   Mysql数据库连接错误!","ERROR")
		return
	}
	return query(sqlStr, db)
}
func GetOracleData(sqlStr string)(list []map[string]string) {
	db, err := utilities.Oracle()
	if err != nil {
		utilities.WriteLog("/orm/query.go:55   Oracle数据库连接错误!","ERROR")
		return
	}
	return query(sqlStr, db)
}
