Gorm用原生sql查问有两种形式:
// 第一种type Result struct { ID int Name string Age int}var result Resultdb.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 stringfunc Byte2Str(b []byte) string { return *(*string)(unsafe.Pointer(&b))}