select查询一条数据 多个字段 的封装函数解决求助

hellsam · · 878 次点击
https://github.com/yudeguang/mysql type MySqlStruct struct { DB *sql.DB } func (m *MySqlStruct) Query(query string, args ...interface{}) ([][]string, error) { stmt, err := m.DB.Prepare(query) if err != nil { return nil, err } defer stmt.Close() rows, err := stmt.Query(args...) if err != nil { return nil, err } defer rows.Close() //获取列数量 columns, err := rows.Columns() if err != nil { return nil, err } lenColumns := len(columns) var result [][]string for rows.Next() { oneColumn := make([]string, lenColumns) oneColumnHasNULL := make([]sql.RawBytes, lenColumns) oneColumnPtr := make([]interface{}, lenColumns) for i := 0; i < lenColumns; i++ { oneColumnPtr[i] = &oneColumnHasNULL[i] } err = rows.Scan(oneColumnPtr...) if err != nil { return nil, err } //处理NULL值 for i, v := range oneColumnHasNULL { if v == nil { oneColumn[i] = "NULL" } else { oneColumn[i] = string(oneColumnHasNULL[i]) } } result = append(result, oneColumn) } return result, nil }
#5
更多评论
这样肯定不行,Scan 必须知道字段数量
#2