查询一条数据 多个字段 , 将在不知道几个字段的情况下封装个函数 查询 返回数组格式
报错了。
不知道如何解决 研究一下午了,没解决
希望高手帮我改改 谢谢了!
~~~
func DualValueTest(singleSql string) []string {
var array []string
var result string
rows, err := DB.Query(singleSql)
if err != nil {
panic(err)
}
defer rows.Close()
i := 0
for rows.Next() {
err = rows.Scan(&result)
array[i] = result
if err != nil {
fmt.Println("多字段查询报错信息:", err.Error())
//panic(err)
}
i++
//Map1 = append(Map1, result)
}
return array
}
然后调用上面函数 获取值方法
array2 := mysql.DualValueTest("select email,tel,logintime from user_list where uid =20")
fmt.Fprintln(w, array2[0])
fmt.Fprintln(w, array2[1])
fmt.Fprintln(w, array2[2])
~~~
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