Postgres 返回 []uint8 而不是 []integer

Joh*_*oah 1 postgresql go pq

我正在将一个整数数组保存到 PostgreSQL 表中,并且在尝试检索它时,我总是得到 []uint8 而不是 []int。我尝试使用 []integer、[]bigint、[]smallint。没有任何效果。该数组最多表示四项,每一项在 1-100 之间,没有浮点数。

我正在使用 Go,并且我有一个 []int 对象,这是字段:

Quantity []int `json:"quantity" db:"quantity"`
Run Code Online (Sandbox Code Playgroud)

我正在尝试修复它,但找不到让 PostgreSQL 返回 []int 的方法。

所有其他表字段都很好用。该Quantity字段的类型integer[]

这是插入查询:

"INSERT INTO products (product_id, name, manufacturer, image_url, quantity, amount, notes, store_id, store_name, owner_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", newProduct.UID, newProduct.Name, newProduct.Manufacturer, newProduct.Image, pq.Array(newProduct.Quantity), newProduct.Amount, newProduct.Notes, newProduct.StoreID, newProduct.StoreName, newProduct.OwnerID);
Run Code Online (Sandbox Code Playgroud)

这就是我尝试获取数据的方式。

err := rows.Scan(&temp.ID, &temp.UID, &temp.Name, &temp.Manufacturer,
        &temp.Image, &temp.Amount, &temp.Notes,
        &temp.StoreID, &temp.OwnerID, &temp.StoreName, &temp.Quantity)
Run Code Online (Sandbox Code Playgroud)

问题仅在于数量。如果我更改temp object[]uint8而不是[]int我确实得到了字节。

Ekl*_*vya 5

pq.Array(&temp.Quantity)

您存储的方式,您也必须以这种方式检索。

err := rows.Scan(&temp.ID, &temp.UID, &temp.Name, &temp.Manufacturer,
        &temp.Image, &temp.Amount, &temp.Notes,
        &temp.StoreID, &temp.OwnerID, &temp.StoreName, pq.Array(&temp.Quantity))
Run Code Online (Sandbox Code Playgroud)

你必须使用支持类型pq.Array()也或实现扫描仪接口。对于整数,您可以使用[]sql.NullInt64[]int64。但最好为 Scanner 和 Valuer 接口使用相同的受支持类型。

在此处查找更多详细信息。