读取数据库的SELECT语句是动态变化的,因此查询出来的列也是变化的。按照网上查找的资料,使用下面的方法进行处理:
cols, err := rows.Columns() // Remember to check err afterwards
vals := make([]interface{}, len(cols))
for i, _ := range cols {
vals[i] = new(sql.RawBytes)
}
for rows.Next() {
err = rows.Scan(vals...)
// Now you can check each element of vals for nil-ness,
// and you can use type introspection and type assertions
// to fetch the column into a typed variable.
}
但是err = rows.Scan(vals...)这一句总是执行不了,报错:sql: Scan error on column index 0: destination not a pointer
我用的具体程序是:
for rows.Next() {
err := rows.Scan(vals...)
checkErr(err)
for i := range vals {
mt.Print(vals[i], " ")
}
fmt.Print("\n")
}<