9. 未知的列
Scan()
函数要求您传递正确数量的目标变量。如果您不知道查询将返回什么结果,该怎么办?
如果您不知道查询将返回多少列,则可以使用 Columns()
查找列名列表。您可以检查此列表的长度以查看有多少列,并且可以使用正确的值数将一个切片传递到 Scan()
中。例如,某些 MySQL 分支会为 SHOW PROCESSLISTLIST
命令返回不同的列,因此您必须为此做好准备,否则会导致错误。这是一种实现方法;还有其他方法:
cols, err := rows.Columns()
if err != nil {
// handle the error
} else {
dest := []interface{}{ // Standard MySQL columns
new(uint64), // id
new(string), // host
new(string), // user
new(string), // db
new(string), // command
new(uint32), // time
new(string), // state
new(string), // info
}
if len(cols) == 11 {
// Percona Server
} else if len(cols) > 8 {
// Handle this case
}
err = rows.Scan(dest...)
// Work with the values in dest
}
如果您不知道列或其类型,则应使用 sql.RawBytes
。
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.
}
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。