我试图从PostgreSQL数据库中获取UUID
数组,这会产生以下错误:
sql: Scan error on column index 0: unsupported Scan, storing driver.Value type []uint8 into type *[]string
获取单个UUID
没有问题,但当它是array
时,Scan
函数会将元素的类型推断为uint8
。
有解决方法/解决方案吗?或者我应该重新考虑我的数据库?
代码:
func FetchListIdsForUser(id string, db *sql.DB) ([]string, error) {
// where the results will be stored
var (
lists []string
)
// statement prep
stmt, err := db.Prepare("select lists from users where object_id = $1")
if err != nil {
formattedError := er.New("FetchListIdsForUser SQL Select: " + err.Error())
log.Println(formattedError)
return nil,formattedError
}
defer stmt.Close()
// query happening
rows, err := stmt.Query(id)
if err != nil {
formattedError := er.New("FetchListIdsForUser SQL Query: " + err.Error())
log.Println(formattedError)
return nil,formattedError
}
defer rows.Close()
// for each row
for rows.Next() {
// scan : this is where the error happens.
err := rows.Scan(&lists)
if err != nil {
formattedError := er.New("FetchListIdsForUser SQL Scan: " + err.Error())
log.Println(formattedError)
return nil,formattedError
}
return lists,nil
}
err = rows.Err()
if err != nil {
formattedError := er.New("FetchListIdsForUser: " + id + " Does Not Exist")
log.Println(formattedError)
return nil,formattedError
}
return nil,er.New("FetchListIdsForUser: " + id + " Does Not Exist")
}
答案 0 :(得分:1)
您的代码可以简化很多:
func FetchListIdsForUser(id string, db *sql.DB) ([]string, error) {
rows, err := db.Query("SELECT unnest(lists) FROM users WHERE object_id = $1", id)
if err != nil {
formattedError := errors.New("FetchListIdsForUser SQL Query: " + err.Error())
return nil, formattedError
}
defer rows.Close()
var lists []string
var list string
for rows.Next() {
// scan every item of the array and append it to lists
err := rows.Scan(&list)
if err != nil {
formattedError := errors.New("FetchListIdsForUser SQL Scan: " + err.Error())
return nil,formattedError
}
lists = append(lists, list)
}
if lists == nil {
// no rows returned
formattedError := errors.New("FetchListIdsForUser: " + id + " Does Not Exist")
return nil, formattedError
}
return lists, nil
}
db.Query()
将为您准备(并缓存)该语句。没有必要手动执行此操作。unnest(lists)
。这将为数组中的每个元素生成一行。lists
。此外,this driver支持开箱即用的扫描阵列。