Gorm 原生Sql 查询

2年前 (2022) 程序员胖胖胖虎阿
179 0 0

Gorm用原生sql查询有两种方式:

// 第一种
type Result struct {
    ID   int
    Name string
    Age  int
}

var result Result
db.Raw("SELECT id, name, age FROM users WHERE id = ?", 3).Scan(&result)


// 第二种
result := map[string]interface{}{}
db.Model(&User{}).First(&result)
// SELECT * FROM `users` ORDER BY `users`.`id` LIMIT 1


//通用使用方式
rows, _ := db.Raw("select * from admin").Rows()
fmt.Println(rows)
res := scanRows2map(rows)
func scanRows2map(rows *sql.Rows) []map[string]string {
    res := make([]map[string]string, 0)               //  定义结果 map
    colTypes, _ := rows.ColumnTypes()                 // 列信息
    var rowParam = make([]interface{}, len(colTypes)) // 传入到 rows.Scan 的参数 数组
    var rowValue = make([]interface{}, len(colTypes)) // 接收数据一行列的数组

    for i, colType := range colTypes {
        rowValue[i] = reflect.New(colType.ScanType())           // 跟据数据库参数类型,创建默认值 和类型
        rowParam[i] = reflect.ValueOf(&rowValue[i]).Interface() // 跟据接收的数据的类型反射出值的地址

    }
    // 遍历
    for rows.Next() {
        rows.Scan(rowParam...) // 赋值到 rowValue 中
        record := make(map[string]string)
        for i, colType := range colTypes {

            if rowValue[i] == nil {
                record[colType.Name()] = ""
            } else {
                record[colType.Name()] = Byte2Str(rowValue[i].([]byte))
            }
        }
        res = append(res, record)
    }
    return res
}

// Byte2Str []byte to string
func Byte2Str(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}
版权声明:程序员胖胖胖虎阿 发表于 2022年11月7日 上午7:40。
转载请注明:Gorm 原生Sql 查询 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...